How to remove an element in Groovy using XmlSlurper?

给你一囗甜甜゛ 提交于 2019-11-29 11:15:17

Try

rootNode.one.replaceNode { }

To complete the answer:

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

Output:

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

Find the node and replace it:

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)

Output:

<?xml version="1.0" encoding="UTF-8"?><root>
  <two>Some text!</two>
</root>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!