tags:

views:

1041

answers:

1

I have an org.w3c.dom.Document instance which I need to convert to an XML string. I know how to do this in Java (using javax.xml.transform facilities), but I wondered whether there is a more "groovy" way of doing this?

I've tried using a the DomToGroovy class, which successfully create a groovy script version of the DOM document. But I'm not sure how I would use this to generate an XML string. I might be barking up the wrong tree...

Any help would be greatly appreciated!

+1  A: 

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)

Leonel
I think it was added in Groovy 1.6. It is not in the Groovy 1.5 that comes with NetBeans 6.5
Patrick