So I have some XML like this:
<bar>
<foo>Something</foo>
<baz>
<foo>Hello</foo>
<zap>Another</zap>
<baz>
<bar>
And I want to remove all the foo nodes. Something like this doesn't work
params = xml.xpath('//foo')
for n in params:
xml.getroot().remove(n)
Giving
ValueError: Element is not a child of this node.
What is a neat way to do this?
etree module. The lxml. etree module implements the extended ElementTree API for XML.
The xpath() method For ElementTree, the xpath method performs a global XPath query against the document (if absolute) or against the root node (if relative): >>> f = StringIO('<foo><bar></bar></foo>') >>> tree = etree.
try:
for elem in xml.xpath( '//foo' ) :
elem.getparent().remove(elem)
remove it from it's parent, not the root ( unless it IS a child of the root element )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With