[英]How can I remove all elements matching an xpath in python using lxml?
So I have some XML like this: 所以我有一些像这样的XML:
<bar>
<foo>Something</foo>
<baz>
<foo>Hello</foo>
<zap>Another</zap>
<baz>
<bar>
And I want to remove all the foo nodes. 我想删除所有foo节点。 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? 什么是一个巧妙的方法来做到这一点?
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 ) 从它的父节点而不是根节点中删除它(除非它是根元素的子节点)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.