【问题标题】:How can I remove all elements matching an xpath in python using lxml?如何使用 lxml 在 python 中删除与 xpath 匹配的所有元素?
【发布时间】:2010-07-29 02:49:01
【问题描述】:

所以我有一些这样的 XML:

<bar>
  <foo>Something</foo>
  <baz>
     <foo>Hello</foo>
     <zap>Another</zap>
  <baz>
<bar>

我想删除所有的 foo 节点。这样的东西是行不通的

params = xml.xpath('//foo')
for n in params:
  xml.getroot().remove(n)

给予

ValueError: Element is not a child of this node.

有什么好的方法可以做到这一点?

【问题讨论】:

    标签: python lxml


    【解决方案1】:

    尝试:

     for elem in xml.xpath( '//foo' ) :
          elem.getparent().remove(elem)
    

    从它的父级而不是根中删除它 (除非它是根元素的子元素)

    【讨论】:

      猜你喜欢
      • 2019-12-11
      • 1970-01-01
      • 1970-01-01
      • 2020-05-24
      • 1970-01-01
      • 1970-01-01
      • 2011-12-20
      • 2012-05-30
      • 2020-11-21
      相关资源
      最近更新 更多