Groovy XML back and forth

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)
writer.toString()
Advertisements

Tags: , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: