Uncommented Bytes

Tuesday, September 30, 2008

Format groovy StreamingMarkupBuilder XML

Playing with groovy this week, and specifically the MarkupBuilder and StreamingMarkupBuilder classes to create XML documents. MarkupBuilder is simple but doesn't handle namespaces in a DSL friendly way. StreamingMarkupBuilder handles namespaces nicely but doesn't pretty-print format the xml in the output. And finding information on how to pretty print xml from StreamingMarkupBuilder is rather difficult on Google and the like, so here is the solution that I found using the Transformer class that ships with the JDK.


String indentXml(xml) {
def factory = TransformerFactory.newInstance()
factory.setAttribute("indent-number", 2);

Transformer transformer = factory.newTransformer()
transformer.setOutputProperty(OutputKeys.INDENT, 'yes')
StreamResult result = new StreamResult(new StringWriter())
transformer.transform(new StreamSource(new ByteArrayInputStream(xml.toString().bytes)), result)
return result.writer.toString()
}

xml is the output from the .bind call on StreamingMarkupBuilder. And the setAttribute call on TransformerFactory is needed to get around a JDK bug.