xml - 使用 Gpath 移动节点
问题描述
给定数据模型
<outerTag>
<tagA>
</tagB>
</tagA>
<tagC>
<interestingContent>
...
</interestingContent>
</tagC>
</outerTag>
我想将子节点移动<interestingContent>
到<tagB>
. 我不知道要移动的节点的可能内容,它们也可能有子节点。我目前正在使用 GPath,并认为像这样简单的东西应该可以工作:
outertag.tagC.childNodes().each { node ->
outerTag.tagA.tagB.appendNode(node)
}
但是,虽然我能够从节点读取名称和文本,appendNode
但似乎并没有奏效。虽然理论上我可以从孩子那里读取属性、文本和名称,使用它来创建一个新节点并附加该节点,但我觉得这没有必要复杂化,特别是因为它需要是一个递归函数,因为节点可以有子节点自己。
解决方案
您的代码稍作改动
def outerTag = new XmlParser().parseText('''<outerTag>
<tagA>
<tagB/>
</tagA>
<tagC>
<interestingContent a="a">1</interestingContent>
<interestingContent a="b">2</interestingContent>
</tagC>
</outerTag>''')
outerTag.tagC[0].children().each { child ->
outerTag.tagA.tagB[0].append(child)
}
//reset value for tagC
outerTag.tagC[0].setValue("")
println groovy.xml.XmlUtil.serialize(outerTag)
推荐阅读
- excel - 使用 excel vba 下载 YouTube 字幕
- google-sheets - 谷歌表格:如何获取与上一列具有相同值的列中的最后一个值?
- python - django admin 向表单字段添加错误
- java - 未找到 jbpm 7.8 业务中心
- javascript - 为什么这个变量没有定义?
- mysql - mysql-js如何插入带有插入id的批量记录
- node.js - GAE - Nodejs - 一个简单的 pubsub 应用程序的内存泄漏 - 超过了软私有内存限制
- c# - 对象值在 linq 中给出对象数组
- android - 无法将字节从活动发送到蓝牙接收器?
- wordpress - 每次在wordpress中加载页面时如何更改背景图像