在 XML 中插入子节点

Insert child node in XML

需要帮助使用 Groovy 在 XML 中的特定节点之后简单插入节点。搜索现有的帖子得出了那个,接近但不够

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()

结果

<?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>

预期结果是 <ns7:custom01>custom01</ns7:custom01> 插入到父 playerDataMap

  1. 您使用 XmlSlurpern 创建 node。但是你应该使用 XmlParser 就像你在上面的行中所做的那样
  2. 您还应该在 nodes.each { it.parent().appendNode(node) }
  3. 行使用 it.parent().append(node)

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