Groovy Beginner Groovy Beginner - 3 months ago 22
Groovy Question

Delete Child Nodes in an XML

i'm trying to remove a child node from an xml. my script is working..but it not removing child nodes... and not just the one i want to remove.

import groovy.xml.*;
def employees='''<Employees>
<Employee>
<ID>123</ID>
<Name>xyz</Name>
<Addresses>
<Address>
<Country>USA</Country>
<ZipCode>40640</ZipCode>
</Address>
</Addresses>
</Employee>
<Employee>
<ID>345</ID>
<Name>abc</Name>
<Addresses>
<Address>
<Country>CA</Country>
<ZipCode>50640</ZipCode>
</Address>
</Addresses>
</Employee>
</Employees>'''
def fields = ['Name','ZipCode']
def xml = new XmlParser().parseText(employees)
xml.Employee.each { node ->
node.children().reverse().each{
if(!fields.contains(it.name())) {
node.remove(it)
}
}
}

XmlUtil.serialize(xml)


How to delete the node ZipCode from each employee in the xml?

Answer

Like below:

import groovy.xml.*

def employees='''<Employees>
                      <Employee>
                         <ID>123</ID>
                         <Name>xyz</Name>
                         <Addresses>
                             <Address>
                                <Country>USA</Country>
                                <ZipCode>40640</ZipCode>
                             </Address>
                          </Addresses>
                      </Employee>
                      <Employee>
                         <ID>345</ID>
                         <Name>abc</Name>
                         <Addresses>
                             <Address>
                                <Country>CA</Country>
                                <ZipCode>50640</ZipCode>
                             </Address>
                          </Addresses>
                      </Employee>
                    </Employees>''' 
def fields = ['Name','ZipCode'] 

def xml = new XmlParser().parseText(employees) 

xml.'**'.findAll { it.name() in fields }*.replaceNode { }

XmlUtil.serialize(xml)

This checks if node name is present in the list of fields while doinf a depth first search. If present then it removes the node. In the above example, Name and ZipCode is removed.