Inserting XML snippet into another XML document in Groovy
The next piece of code should insert the XML snippet into the body, right after elem.
def body = '''
<parent>
<child>
<elem>
<name>Test</name>
</elem>
</child>
</parent>
'''
def fragment = '''
<foo>
<bar>hello!</bar>
<baz/>
</foo>
'''
def bodyNode = new XmlParser().parseText(body)
def fragmentNode = new XmlParser().parseText(fragment)
bodyNode.child*.appendNode(fragmentNode)
def newFileName= '/Users/xxx/out.xml'
def writer = new FileWriter(newFileName)
new XmlNodePrinter(new PrintWriter(writer)).print(bodyNode)
Expected content out.xml:
<parent>
<child>
<elem>
<name>Test</name>
</elem>
<foo>
<bar>hello!</bar>
<baz/>
</foo>
</child>
</parent>
However, I get instead:
<parent>
<child>
<elem>
<name>Test</name>
</elem>
<foo/>
</child>
</parent>
As you can see, the content of the foo element has been omitted. What is the reason for this behavior and how can I reach the correct conclusion?
+3
source to share
2 answers
Cause
use appendNode()
instead of append()
. Try this instead:
bodyNode.child*.append(fragmentNode)
As an alternative
This is one way to get the correct output with XmlSlurper
:
def body = '''
<parent>
<child>
<elem>
<name>Test</name>
</elem>
</child>
</parent>
'''
def fragment = '''
<foo>
<bar>hello!</bar>
<baz/>
</foo>
'''
def slurper = new XmlSlurper( false, false, false )
def bodyNode = slurper.parseText( body )
def fragmentNode = slurper.parseText( fragment )
bodyNode.child << fragmentNode
def sw = new StringWriter()
groovy.xml.XmlUtil.serialize(bodyNode, sw)
println sw.toString()
+3
source to share
Working example using XmlParser
:
import groovy.xml.XmlUtil
def body = '''
<parent>
<child>
<elem>
<name>Test</name>
</elem>
</child>
</parent>
'''
def fragment = '''
<foo>
<bar>hello!</bar>
<baz/>
</foo>
'''
def bodyNode = new XmlParser().parseText(body)
def fragmentNode = new XmlParser().parseText(fragment)
bodyNode.child[0].children().add(fragmentNode)
println(XmlUtil.serialize(bodyNode))
+1
source to share