You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Groovy XmlSlurper:如何仅追加子节点内容避免重复父标签?

解决XmlSlurper追加节点时重复标签的问题

你遇到的问题是因为调用root2(xmlObject2)时,相当于新建了一个<root2>节点,同时把原本就是<root2>类型的xmlObject2作为它的子节点,所以出现了嵌套重复的标签。可以用以下两种方式解决:

方法1:直接追加整个xmlObject2节点

直接将xmlObject2作为节点追加到xmlObject中,无需额外包裹:

def slurper = new XmlSlurper()
def xmlObject = slurper.parseText("<root />")
def xmlObject2 = slurper.parseText("<root2><child1>hello</child1><child2>world</child2></root2>")

// 直接追加xmlObject2节点
xmlObject.appendNode(xmlObject2)

// 输出验证
def writer = new StringWriter()
new XmlNodePrinter(new PrintWriter(writer)).print(xmlObject)
println writer.toString()

运行后会得到你想要的XML结构:

<root>
  <root2>
    <child1>hello</child1>
    <child2>world</child2>
  </root2>
</root>

方法2:手动构建root2并追加其子节点

如果需要更灵活地控制节点内容,可以遍历xmlObject2的子节点,将它们添加到新建的root2节点中:

def slurper = new XmlSlurper()
def xmlObject = slurper.parseText("<root />")
def xmlObject2 = slurper.parseText("<root2><child1>hello</child1><child2>world</child2></root2>")

xmlObject.appendNode {
    root2 {
        // 遍历xmlObject2的所有子节点并追加
        xmlObject2.children().each { childNode ->
            delegate.appendNode(childNode)
        }
    }
}

// 输出验证
def writer = new StringWriter()
new XmlNodePrinter(new PrintWriter(writer)).print(xmlObject)
println writer.toString()

这种方式同样能得到目标XML结构,适合需要对节点做额外处理的场景。


内容的提问来源于stack exchange,提问作者Suwandi Cahyadi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 09:40:09