but I wondered whether there is a more "groovy" way of doing this?
There sure is: class groovy.xml.XmlUtil
I'm not sure what was the version of Groovy when this class was added, but I guess it was an early version.
Edit: class groovy.xml.XmlUtil exists since version 1.6.0; in version 1.5.x, it was named groovy.xml.dom.DOMUtil. In either version, this class doesn't do anything too groovy; if you look at its source, you'll see it's just a wrapper around java.xml.transform
. However, I really appreciate that the Groovy GDK provides a simple way to do such a common operation (writing xml to a string), while the Java JDK fails to.
Example:
import javax.xml.parsers.DocumentBuilderFactory
import groovy.xml.XmlUtil
def fileName = 'build.xml'
def builder = DocumentBuilderFactory.newInstance().newDocumentBuilder()
def inputStream = new FileInputStream(fileName)
def doc = builder.parse(inputStream)
println XmlUtil.serialize(doc.documentElement)
Always look at the Groovy API and the Groovy extensions to the JDK before rolling your own solution (a lesson I learned the hard way)