我正在尝试从xml中删除子节点。我的脚本正在运行..但它不会删除子节点......而不仅仅是我要删除的节点。
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)
如何从xml中的每个员工中删除节点ZipCode?
答案 0 :(得分:2)
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.