0

I want to remove some elements from an XML file using groovy, however this does not seem to work.

Any ideas how to solve this?

def DeploymentDescriptors = new XmlSlurper().parse("pathToMyXMLFile")
DeploymentDescriptors.NameValuePairs.NameValuePair.each {
if(it.name == 'B')
   it.replaceNode{}
}

XML File

<DeploymentDescriptors>
    <NameValuePairs>
        <NameValuePair>
            <name>A</name>
            <value>Value A</value>
        </NameValuePair>
        <NameValuePair>
            <name>B</name>
            <value>Value B</value>
        </NameValuePair>
        <NameValuePair>
            <name>C</name>
            <value>Value C</value>
        </NameValuePair>
    </NameValuePairs>
</DeploymentDescriptors>
Opal
  • 81,889
  • 28
  • 189
  • 210
user955732
  • 1,330
  • 3
  • 21
  • 48

1 Answers1

3

XmlSlurper doesn't change the processed XML until there's a need. If You serialize it You'll see the effect.

Here's working example:

import groovy.xml.StreamingMarkupBuilder
import groovy.xml.XmlUtil
def xml = """
<DeploymentDescriptors>
    <NameValuePairs>
        <NameValuePair>
            <name>A</name>
            <value>Value A</value>
        </NameValuePair>
        <NameValuePair>
            <name>B</name>
            <value>Value B</value>
        </NameValuePair>
        <NameValuePair>
            <name>C</name>
            <value>Value C</value>
        </NameValuePair>
    </NameValuePairs>
</DeploymentDescriptors>"""

def parsed = new XmlSlurper().parseText(xml)
parsed.NameValuePairs.NameValuePair.findAll { it.name.text() == 'B' }*.replaceNode{}
println XmlUtil.serialize(new StreamingMarkupBuilder().bind {
  mkp.yield parsed
} )
Opal
  • 81,889
  • 28
  • 189
  • 210