Nis*_*nce 3 python xml iterator elementtree xml.etree
如何删除当前节点,同时按getiterator()功能从根遍历所有节点?
import xml.etree.ElementTree as ET
tree = ET.parse('file.xml')
root = tree.getroot()
for node in root.getiterator():
#if some condition:
#remove(node)
Run Code Online (Sandbox Code Playgroud)
如果不知道父节点,则无法删除节点,但xml.etree程序包不会为您提供从给定节点访问父节点的任何方法.
解决这个问题的唯一方法是匹配父节点:
for node in root.iter():
if some_condition_matches_parent:
for child in list(node.iter()):
if some_condition_matches_child:
node.remove(child)
Run Code Online (Sandbox Code Playgroud)
如果切换到lxml库(实现相同的API,但具有其他增强功能),则可以从任何给定节点检索父节点:
node.getparent().remove(node)
Run Code Online (Sandbox Code Playgroud)
注意,虽然纯Python实现Element.getiterator()返回一个列表对象,但在ElementTree模块的C实现中(Python 2上的单独导入,如果可用,在Python 3上透明导入),该getiterator()方法返回一个需要副本的实时生成器.制作.
最重要的是,该Element.getiterator()方法已在Python 3.2中弃用,并将在Python 3.9中完全删除.我用node.iter()外循环和list(node.iter())内部替换了它的用法.
| 归档时间: |
|
| 查看次数: |
2345 次 |
| 最近记录: |