Sadly, and annoyingly, groovy.util.slurpersupport.NodeChild doesn’t have a nice toString() implementation when dealing with results obtained from groovy.util.XmlSlurper. For convenience, you can add the following meta-method to NodeChild to serialize xml nodes:

NodeChild.metaClass.toXmlString = {
	def self = delegate
	new StreamingMarkupBuilder().bind { 
		delegate.mkp.xmlDeclaration() // Use this if you want an XML declaration
		delegate.out << self
	}.toString()
}

In grails, you would typically run such code from a thread-safe location such as from within a plugin or inside BootStrap.groovy. Then, in your application you can use:

def xml = new XmlSlurper().parseText('<a>b</a>')
println xml.toXmlString()

This is handy when building REST APIs that require both text and node based version of xml, such as an API proxy.

Advertisements