开发者

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

开发者 https://www.devze.com 2023-01-09 21:08 出处:网络
So I have some XML like this: <bar> <foo>Something</foo> <baz> <foo>Hello</foo>

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 wa开发者_Go百科y to do this?


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 )

0

精彩评论

暂无评论...
验证码 换一张
取 消