Posts Tagged ‘XmlNodePrinter’

Groovy XML back and forth

February 8, 2010

Groovy has convenient classes for working with XML. You can use the XmlParser (or XmlSlurper) if you want to parse existing XML into a tree structure. You can use the XmlBuilder, if you want to build XML from scratch. But what if you want to read existing XML, change it, and write it back again? It’s easy. You can use the XmlNodePrinter object for that:

def xmltree = new XmlParser.parseText("<node text='hello'>")
xmltree.@text = 'goodbye'
StringWriter writer = new StringWriter()
new XmlNodePrinter(new PrintWriter(writer)).print(xmltree)