Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove all elements matching an xpath in python using lxml?

Tags:

python

lxml

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?

like image 789
Michael Anderson Avatar asked Jul 29 '10 02:07

Michael Anderson


People also ask

What is etree in lxml?

etree module. The lxml. etree module implements the extended ElementTree API for XML.

What is Xpath in LXML?

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.


1 Answers

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 )

like image 68
Steven D. Majewski Avatar answered Oct 27 '22 00:10

Steven D. Majewski