Search code examples
groovyxmlslurper

Groovy XmlSlurper appendNode of child content only


I have the following xml object:

def slurper = new XmlSlurper()
def xmlObject = slurper.parseText("<root />")

def xmlObject2 = slurper.parseText("<root2><child1>hello</child1><child2>world</child2></root2>")

Now, the objective is to have the following XML format:

<root>
<root2>
<child1>hello</child1>
<child2>world</child2>
<root2>
</root>

If I use appendNode like this:

xmlObject.appendNode {
   root2(xmlObject2)
}

I would get:

<root>
<root2>
<root2>
<child1>hello</child1>
<child2>world</child2>
<root2>
<root2>
</root>

I would have 2 root2. How to appendNode of only the child content? Or appendNode without any tag name?

Thank you.


Solution

  • Why don't you just add the node as xmlObject.appendNode(xmlObject2)? Here is what I've come up with:

    import groovy.xml.XmlUtil
    
    def slurper = new XmlSlurper()
    def xmlObject = slurper.parseText("<root />")
    
    def xmlObject2 = slurper.parseText("<root2><child1>hello</child1><child2>world</child2></root2>")
    
    xmlObject.appendNode(xmlObject2)
    
    println XmlUtil.serialize(xmlObject)
    

    It produces:

    <?xml version="1.0" encoding="UTF-8"?>
    <root>
      <root2>
        <child1>hello</child1>
        <child2>world</child2>
      </root2>
    </root>
    

    Looks like the result you wanted. I hope it helps.