【发布时间】:2019-03-18 05:05:31
【问题描述】:
在使用 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>
预期结果是在父 playerDataMap 下插入<ns7:custom01>custom01</ns7:custom01>
【问题讨论】:
标签: groovy xml-parsing xmlslurper