https://stackoverflow.com/questions/7981840/how-to-remove-an-element-in-lxml

 

import lxml.etree as et

xml="""
<groceries>
  <fruit state="rotten">apple</fruit>
  <fruit state="fresh">pear</fruit>
  <punnet>
    <fruit state="rotten">strawberry</fruit>
    <fruit state="fresh">blueberry</fruit>
  </punnet>
  <fruit state="fresh">starfruit</fruit>
  <fruit state="rotten">mango</fruit>
  <fruit state="fresh">peach</fruit>
</groceries>
"""

tree=et.fromstring(xml)

for bad in tree.xpath("//fruit[@state='rotten']"):
    bad.getparent().remove(bad)

print et.tostring(tree, pretty_print=True)

相关文章:

  • 2022-01-20
  • 2022-12-23
  • 2021-12-23
  • 2021-10-27
  • 2022-12-23
  • 2021-09-30
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-06-03
  • 2022-03-04
  • 2022-12-23
  • 2022-12-23
  • 2021-11-28
  • 2022-12-23
相关资源
相似解决方案