How to REALLY remove a node via XMLParser:
x=\'\'\'
a
b
Removing nodes works pretty much like other DOM APIs. You have to pass the node you want to delete to the remove method of its parent.
Also the =
operator is the assignment operator in Groovy. it.@C1 = 'a'
would assign 'a'
to the C1
attribute of each B
node in the document. Since the result of that assignment is 'a'
, which is coerced to true
by Groovy, find
will always return the first node it encounters.
xml=new XmlParser().parseText(x)
def nodeToDel=xml.A.B.C1.find { it.text() == 'a' }
def parent = nodeToDel.parent()
parent.remove(nodeToDel)
Improving solution of Justin Piper, with a fully working example:
def xml = new XmlParser().parseText('''
<root>
<element id="10" />
<element id="20" />
</root>
''')
def nodeToDel = xml.find { it["@id"] == '20' }
if (nodeToDel) {
nodeToDel.parent().remove(nodeToDel)
}
println xml