Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.5k views
in Technique[技术] by (71.8m points)

xml - How to remove an element in Groovy using XmlSlurper?

For example, how can I remove all tags with name one in rootNode programmatically?

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

I tried

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

but it reported:

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]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 )

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...