groovy - 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
解决方案
- 您
XmlSlurper
使用node
从n
. 但是您应该XmlParser
像在上面的行中那样使用 - 您还应该
it.parent().append(node)
在与nodes.each { it.parent().appendNode(node) }
应用这两个更改后,它将按您的预期工作
推荐阅读
- c - C 新手;使用数组。不良输出
- node.js - 如何在对话框流中将默认日期值设置为当前日期
- mysql - 如何解决“错误无法添加外键约束”?
- python - 如何将下载的 pdf 文件存储到 Mongo DB
- python - 将字符串连接到从另一个数据帧映射的 MultiIndex 级别
- angularjs - 角度材料布局指令不起作用
- apache-camel - 使用 Apache camel 读取 xml 文件并将其发送到休息服务
- imagemagick - 如何在imagick中实现像翘曲一样的Photoshop
- ios - 使用 UIGraphicsPDFRenderer 创建 PDF 时添加页脚,如“y 页 x”
- node.js - 如何在 Heroku 上部署 reactJS + nodeJS 应用程序?