#!/usr/share/groovy/bin/groovySuggestions for alternatives would be appreciated!
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()
}
Friday, April 3, 2009
Groovy: Pretty Printing XML
A script for pretty printing XML in Groovy:
Subscribe to:
Post Comments (Atom)
If you switch languages...
ReplyDelete#!/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.
That being said, the JVM is too slow to start up if you really want a good shell utility. I like:
ReplyDelete#!/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
Thanks Steven, works great.
ReplyDeleteOn Groovy 1.8, you can use:
ReplyDelete#!/usr/share/groovy/bin/groovy
import groovy.xml.XmlUtil
def xml = new File(args[0]).text
println XmlUtil.serialize(xml)
Still much too slow to start up...
ReplyDelete