首页 > 解决方案 > 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

标签: groovyxml-parsingxmlslurper

解决方案


  1. XmlSlurper使用noden. 但是您应该XmlParser像在上面的行中那样使用
  2. 您还应该it.parent().append(node)在与nodes.each { it.parent().appendNode(node) }

应用这两个更改后,它将按您的预期工作


推荐阅读