如何在python xml.etree.ElemenTree中删除迭代器内的节点 [英] How to remove a node inside an iterator in python xml.etree.ElemenTree
本文介绍了如何在python xml.etree.ElemenTree中删除迭代器内的节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何删除当前节点,同时通过 getiterator()
函数从根遍历所有节点?
How to remove the current node, while iterating through all nodes from root by getiterator()
function?
import xml.etree.ElementTree as ET
tree = ET.parse('file.xml')
root = tree.getroot()
for node in root.getiterator():
#if some condition:
#remove(node)
推荐答案
您不能在不知道父节点的情况下删除节点,但 xml.etree
包不能没有办法从给定节点访问父节点。
You can't remove nodes without knowing the parent, but the xml.etree
package doesn't give you any way to access a parent from a given node.
唯一的方法是匹配父节点:
The only way around this is matching the parent node instead:
for node in root.getiterator():
if some_condition_matches_parent:
for child in node.getiterator():
if some_condition_matches_child:
node.remove(child)
如果切换到 lxml
library(实现相同的API,但是通过其他增强功能),可以从任何给定节点检索父节点:
If you switch to the lxml
library (which implements the same API, but with additional enhancements), you can retrieve the parent node from any given node:
node.getparent().remove(node)
这篇关于如何在python xml.etree.ElemenTree中删除迭代器内的节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文