我需要根据属性的内容,使用python的lxml完全删除元素。示例:
import lxml.etree as et
xml="""
<groceries>
<fruit state="rotten">apple</fruit>
<fruit state="fresh">pear</fruit>
<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\']"):
#remove this element from the tree
print et.tostring(tree, pretty_print=True)
我想打印:
<groceries>
<fruit state="fresh">pear</fruit>
<fruit state="fresh">starfruit</fruit>
<fruit state="fresh">peach</fruit>
</groceries>
有没有办法在不存储临时变量并手动打印到该变量的情况下执行此操作,如:
newxml="<groceries>\n"
for elt in tree.xpath('//fruit[@state=\'fresh\']'):
newxml+=et.tostring(elt)
newxml+="</groceries>"
您正在寻找
remove
函数。调用树的remove方法并向其传递要删除的子元素。结果:
我遇到了一种情况:
div.remove(script)
将删除我无意删除的text here
部分。在回答here之后,我发现
etree.strip_elements
对我来说是一个更好的解决方案,您可以控制是否使用with_tail=(bool)
参数删除后面的文本。但我仍然不知道这是否可以对标记使用xpath过滤器。把这个放在通知处。
这是医生:
使用xmlement的^{} 方法:
如果必须与@Acorn版本进行比较,即使要删除的元素不在xml的根节点下,我的版本也可以工作。
相关问题 更多 >
编程相关推荐