Search code examples
groovyxml-parsingxmlslurper

Insert child node in XML


need help with simple inserting node after specific one in XML using Groovy. Searching through the existing posts came to that, closer but not enough

import groovy.xml.*

def x='''<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns7:setPlayerInfoRequest xmlns:ns7="http://www.playtech.com/services/player-management">
    <ns7:behaviourType>Create</ns7:behaviourType>
    <ns7:playerDataMap>
        <ns7:currency>${p_currency}</ns7:currency>
    </ns7:playerDataMap>
</ns7:setPlayerInfoRequest>'''

def n = '''<ns7:custom01>custom01</ns7:custom01>'''

def xml=new XmlParser().parseText(x)

def node = new XmlSlurper(false,false).parseText(n)

def nodes = xml.'**'.findAll{ it.name().localPart == 'currency' }

nodes.each{it.parent().appendNode(node)}

XmlUtil.serialize(xml).toString()

Result

<?xml version="1.0" encoding="UTF-8"?><ns7:setPlayerInfoRequest xmlns:ns7="http://www.playtech.com/services/player-management">
  <ns7:behaviourType>Create</ns7:behaviourType>
  <ns7:playerDataMap>
    <ns7:currency>${p_currency}</ns7:currency>
    <custom01/>
  </ns7:playerDataMap>
</ns7:setPlayerInfoRequest>

Expected result is to have <ns7:custom01>custom01</ns7:custom01> inserted under parent playerDataMap


Solution

    1. You use XmlSlurper to create node from n. But you should use XmlParser as you already do at the line above
    2. You should also use it.parent().append(node) at the line with nodes.each { it.parent().appendNode(node) }

    After applying these two changes, it will work as you expect