首页 > 解决方案 > 使用 Gpath 移动节点

问题描述

给定数据模型

<outerTag>
    <tagA>
        </tagB>
    </tagA>
    <tagC>
        <interestingContent>
           ...
        </interestingContent>
    </tagC> 
</outerTag>    

我想将子节点移动<interestingContent><tagB>. 我不知道要移动的节点的可能内容,它们也可能有子节点。我目前正在使用 GPath,并认为像这样简单的东西应该可以工作:

outertag.tagC.childNodes().each { node ->
    outerTag.tagA.tagB.appendNode(node)
}

但是,虽然我能够从节点读取名称和文本,appendNode但似乎并没有奏效。虽然理论上我可以从孩子那里读取属性、文本和名称,使用它来创建一个新节点并附加该节点,但我觉得这没有必要复杂化,特别是因为它需要是一个递归函数,因为节点可以有子节点自己。

标签: xmlgroovygpath

解决方案


您的代码稍作改动

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)

推荐阅读