如何使用 XmlSlurper 删除 Groovy 中的元素?

How to remove an element in Groovy using XmlSlurper?

例如,如何以编程方式删除 rootNode 中名称为 one 的所有标签?

def rootNode = new XmlSlurper().parseText(
    '<root><one a1="uno!"/><two>Some text!</two></root>' )

我试过了

rootNode.children().removeAll{ it.name() == 'one' }

但它报告:

groovy.lang.MissingMethodException: No signature of method: groovy.util.slurpersupport.NodeChildren.removeAll() is applicable for argument types: (DUMMY$_closure1_closure2) values: [DUMMY$_closure1_closure2@6c5f92d3]

尝试

rootNode.one.replaceNode { }

完成答案:

def rootNode = new XmlSlurper().parseText (
    '<root><one a1="uno!"/><two>Some text!</two></root>' 
)

rootNode.one.replaceNode { }

println groovy.xml.XmlUtil.serialize( rootNode )
import groovy.xml.*
String xml = '<root><one a1="uno!"/><two>Some text!</two></root>'
def root = new XmlSlurper().parseText(xml)

root.one.replaceNode{}
def newRoot = new StreamingMarkupBuilder().bind {
    mkp.yield root
}.toString()

println xml
println newRoot

输出:

<root><one a1="uno!"/><two>Some text!</two></root>
<root><two>Some text!</two></root>

找到节点并替换它:

import groovy.xml.XmlUtil

def rootNode = new XmlSlurper().parseText(
    '<root><one a1="uno!"/><two>Some text!</two></root>' )

rootNode.children().findAll { it.name() == 'one' }.replaceNode {}

println XmlUtil.serialize(rootNode)

输出:

<?xml version="1.0" encoding="UTF-8"?><root>
  <two>Some text!</two>
</root>