Using Groovy to pretty print XML and export to a file


March 15th 2022


Recently, I received a large XML document that was rendered as a single line in a file, and so I wanted to write the formatted XML to a new file. Here's the Groovy script I wrote to do this:

import groovy.xml.*

if(args == null || args.length == 0) {
  println "Please pass the name of the file as the first argument!"
  return
}

String fileName = args[0]
String outFileName = fileName.replaceAll(".xml", "-pretty.xml");

def xml = new XmlSlurper().parse(new File("${fileName}"))

def file = new File("${outFileName}")
file.write(XmlUtil.serialize(xml))

Hope that helps someone!

I'm an "old" programmer who has been blogging for almost 20 years now. In 2017, I started Highline Solutions, a consulting company that helps with software architecture and full-stack development. I have two degrees from Carnegie Mellon University, one practical (Information and Decision Systems) and one not so much (Philosophy - thesis here). Pittsburgh, PA is my home where I live with my wife and 3 energetic boys.
I recently released a web app called TechRez, a "better resume for tech". The idea is that instead of sending out the same-old static PDF resume that's jam packed with buzz words and spans multiple pages, you can create a TechRez, which is modern, visual, and interactive. Try it out for free!
Got a Comment?
Comments (0)

 None so far!