xmlgroovy

Add XML node dynamically with groovy


I have an XML similarly like below

<root>
<item>
<refitemid>10</refitemid>
</item>
</root>
    

my requirement is first to add one node <additional_info> to , then add new node to <additional_info> base upon the fetched data so that the new XML would present as below

<root>
<item>
<refitemid>10</refitemid>
<additional_info>
<sn><id>1</id></sn>
<sn><id>2</id></sn>
</additional_info>
</item>
</root>
    

I tried to achieve this with below groovy script.

def oPayload = new XmlSlurper().parseText(message.getBody() as String); //get above original XML data
if (oPayload.root.item.additional_info == "" || oPayload.root.item.additional_info == null) {
    oPayload.root.item.appendNode {
        additional_info {}
    }
}
for (int i = 1; i < 3; i++) {
    oPayload.root.item.additional_info.appendNode {
        sn {
            id(i.text())
        }
    }
}

oPayload = XmlUtil.serialize(oPayload)
    

unfortunately, above code is not working at all, as the result(in oPayload) will become as below:

<root>
<item>
<refitemid>10</refitemid>
</additional_info>
</item>
</root>
    

Can you please share your idea how to achieve the requirement? thanks a lot.


Solution

  • If you use XMLParser, made it a bit easier in my opinion:

    
    import groovy.xml.XmlParser
    import groovy.xml.XmlNodePrinter
    
    def xmlText = '''<root>
    <item>
    <refitemid>10</refitemid>
    </item>
    </root>'''
    
    def root = new XmlParser().parseText(xmlText)
    def item = root.item[0]
    
    def additionalInfo = item.additional_info?.first() ?: item.appendNode('additional_info')
    
    (1..2).each { i ->
        additionalInfo.appendNode('sn').appendNode('id', i.toString())
    }
    
    def writer = new StringWriter()
    new XmlNodePrinter(new PrintWriter(writer)).with {
        preserveWhitespace = true
        print(root)
    }
    
    println writer.toString()