xmlslurper remove node from xml by child value

366 views Asked by At

I need to remove the node "row" from my XML below if the value of "field1" is equal to a certain value.

<root>
<row>
    <content type="application/xml">
        <properties>
            <field1>AAA</field1>
            <field2>001</field2>
        </properties>
    </content>
</row>
<row>
    <content type="application/xml">
        <properties>
            <field1>BBB</field1>
            <field2>001</field2>
        </properties>
    </content>
</row>
<row>
    <content type="application/xml">
        <properties>
            <field1>CCC</field1>
            <field2>001</field2>
        </properties>
    </content>
</row></root>

I tried this piece of code but it leaves the XML unchanged.

root.'**'.findAll { it.name() == 'row' & it.field1.text() == 'BBB'}*.replaceNode{}

How can I achieve it?

1

There are 1 answers

0
daggett On
def xml='''
<root>
<row>
    <content type="application/xml">
        <properties>
            <field1>AAA</field1>
            <field2>001</field2>
        </properties>
    </content>
</row>
<row>
    <content type="application/xml">
        <properties>
            <field1>BBB</field1>
            <field2>001</field2>
        </properties>
    </content>
</row>
<row>
    <content type="application/xml">
        <properties>
            <field1>CCC</field1>
            <field2>001</field2>
        </properties>
    </content>
</row></root>
'''

def root = new XmlSlurper().parseText(xml)

root.row.findAll { it.content.properties.field1.text()=='BBB' }*.replaceNode{}

groovy.xml.XmlUtil.serialize(root)