【问题标题】:Insert child node in XML在 XML 中插入子节点
【发布时间】: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 下插入&lt;ns7:custom01&gt;custom01&lt;/ns7:custom01&gt;

【问题讨论】:

    标签: groovy xml-parsing xmlslurper


    【解决方案1】:
    1. 您使用XmlSlurpern 创建node。但是您应该使用XmlParser,就像您在上面的行中所做的那样
    2. 您还应该在与nodes.each { it.parent().appendNode(node) } 的行中使用it.parent().append(node)

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-15
      • 1970-01-01
      • 2018-11-28
      • 1970-01-01
      • 2021-08-03
      • 1970-01-01
      • 2020-10-17
      相关资源
      最近更新 更多