Friday, April 3, 2009

Groovy: Pretty Printing XML

A script for pretty printing XML in Groovy:
#!/usr/share/groovy/bin/groovy
import org.xml.sax.SAXParseException

def xml = new File(args[0]).text
def stringWriter = new StringWriter()
def printWriter = new PrintWriter(stringWriter)

try {
def node = new XmlParser().parseText(xml)
new XmlNodePrinter(printWriter).print(node)
println stringWriter.toString()
} catch(SAXParseException spe) {
println spe.getMessage()
}
Suggestions for alternatives would be appreciated!

5 comments:

  1. If you switch languages...
    #!/usr/bin/java -cp js.jar org.mozilla.javascript.tools.shell.Main
    print(new XML(readFile(arguments[0])));

    The only downside is that the JSR-223 JavaScript environment included with JavaSE 6 doesn't include the XML support, so you have to provide your own js.jar.

    ReplyDelete
  2. That being said, the JVM is too slow to start up if you really want a good shell utility. I like:

    #!/bin/bash

    xsltproc - $@ <<EOF
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>
    <xsl:template match="@*|node()">
    <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
    </xsl:template>
    </xsl:stylesheet>
    EOF


    Use like:
    $ indent.sh file1.xml file2.xml file3.xml

    ReplyDelete
  3. Thanks Steven, works great.

    ReplyDelete
  4. On Groovy 1.8, you can use:

    #!/usr/share/groovy/bin/groovy

    import groovy.xml.XmlUtil

    def xml = new File(args[0]).text
    println XmlUtil.serialize(xml)

    ReplyDelete
  5. Still much too slow to start up...

    ReplyDelete