Search code examples
xmlgroovy

Get a node as raw XML in Groovy


Provided I have an XML structure:

<a>
  <b>
    <c>aaa</c>
    <d a="42"/>
  </b>
</a>

I want to get the b-node as the original XML String:

<b>
  <c>aaa</c>
  <d a="42"/>
</b>

I tried using XmlSlurper.text(), but it returns only the aaa.

Is it possible to yield the raw XML from the node, without re-creating it with XmlBuilder?

UPDATE

I ended up using the following:

StringWriter sw = new StringWriter()
XmlNodePrinter p = new XmlNodePrinter( new IndentPrinter( sw, '', false, false ), "'" )
p.namespaceAware = false
node.children().each p.&print

println sw

Solution

  • You can use XmlUtil.serialize():

    import groovy.xml.*
    def xmlString = '''<a>
      <b>
        <c>aaa</c>
        <d a="42"/>
      </b>
    </a>'''
    def bNode = new XmlSlurper().parseText(xmlString).b
    
    def bXML = XmlUtil.serialize(bNode)
    
    println(bXML)