Org.w3c.dom.Document to XML string using Groovy

I have an instance of org.w3c.dom.Document that I need to convert to an XML string. I know how to do this in Java (using the features of javax.xml.transform), but I wondered if there is a β€œgroovy” way to do this?

I tried using the DomToGroovy class, which successfully creates a version of the groovy script DOM document. But I'm not sure how to use this to create an XML string. I could bark the wrong tree ...

Any help would be greatly appreciated!

+3
source share
2 answers

but I thought, is there a way to do this "groovy"?

Required: class groovy.xml.XmlUtil

, Groovy, , , .

: groovy.xml.XmlUtil 1.6.0; 1.5.x groovy.xml.dom.DOMUtil. groovy; , java.xml.transform. , , Groovy GDK ​​ ( xml ), Java JDK .

:

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)

Groovy API Groovy JDK (, )

+3

groovy

> def doc = groovy.xml.DOMBuilder.newInstance().parseText("<foo count='42'><bar/><foo>")
> doc.documentElement as String
<foo count="42">
  <bar/>
</foo>
+1

Source: https://habr.com/ru/post/1711563/


All Articles