How to remove an element in Groovy using XmlSlurper?
Asked Answered
P

3

5

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]
Polacca answered 23/11, 2015 at 2:45 Comment(0)
A
5

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 )
Abecedary answered 23/11, 2015 at 3:16 Comment(0)
D
3

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>
Depersonalization answered 23/11, 2015 at 14:42 Comment(0)
S
0
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>
Samanthasamanthia answered 23/11, 2015 at 3:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.