Skip to main content
 首页 » 编程设计

python之从已解析的 XML 树中删除元素会中断迭代

2025年04月02日17虾米姐

我想解析一个 xml 文件,然后通过删除选定的元素来处理结果树。我的问题是删除元素会破坏迭代元素的循环。

考虑以下 xml 数据:

<results> 
    <group> 
        <a /> 
        <b /> 
        <c /> 
    </group> 
</results> 

和代码:

import xml.etree.ElementTree as ET 
 
def showGroup(group,s): 
    print(s + '  len=' + str(len(group))) 
    print('<group>' ) 
    for e in group: 
        print('   <' + e.tag + '>') 
    print('</group>\n') 
 
def processGroup(group): 
    for e in group: 
        if e.tag != 'a': 
            group.remove(e) 
            showGroup(group,'removed <' + e.tag + '>') 
 
tree = ET.parse('x.xml') 
root = tree.getroot() 
 
for group in root: 
    processGroup(group) 

我希望 for 循环处理元素 <a> , <b> , 和 <c>为了。特别是:

  1. 处理<a>不应删除任何元素
  2. 处理<b>应该删除 <b>
  3. 处理<c>应该删除 <c>

我希望生成的树在 <group> 中有一个元素(<a> 元素),并且 len(group) 将返回 1。

相反,经过处理<b> , for 循环决定结束测试已经满足,它不处理元素 <c> .如果是,<c>将被删除。相反,我只剩下一棵包含元素 <a> 的树。和 <c> , len(group) 返回 2。

在删除选定元素的同时处理所有三个元素需要做什么? PS:欢迎任何关于风格或更好的做事方式的评论。

更新:如果删除元素后没有代码,一个丑陋的 hack 以牺牲一些效率为代价“修复”了这个问题。但是在我的真实程序中,剪枝循环之后有很多代码。

for e in group: 
    if e.tag != 'a': 
        group.remove(e) 
        showGroup(group,'removed <' + e.tag + '>') 
        processGroup(group) 

我假设如果 for 循环被打乱,那么从开头的组重新开始可能会解决问题。递归是一种简洁的方法 - 以重新处理所有已检查但未删除的元素为代价。

我对这个解决方案不满意。

请您参考如下方法:

问题是你正在从你正在迭代的东西中删除元素,当你删除一个元素时,剩余的元素会移动,所以你最终可以删除不正确的元素:

一个简单的解决方案是遍历树的副本或使用reversed:

复制:

 def processGroup(group): 
    # creates a shallow copy so we are removing from the original 
    # but iterating over a copy.  
    for e in group[:]: 
        if e.tag != 'a': 
            group.remove(e) 
            showGroup(group,'removed <' + e.tag + '>') 

反转:

def processGroup(group): 
    # starts at the end, as the container shrinks. 
    # when an element is removed, we still see 
    # elements at the same position when we started out loop. 
    for e in reversed(group): 
        if e.tag != 'a': 
            group.remove(e) 
            showGroup(group,'removed <' + e.tag + '>') 

使用复制逻辑:

In [7]: tree = ET.parse('test.xml') 
 
In [8]: root = tree.getroot() 
 
In [9]: for group in root: 
   ...:         processGroup(group) 
   ...:      
removed <b>  len=2 
<group> 
   <a> 
   <c> 
</group> 
 
removed <c>  len=1 
<group> 
   <a> 
</group> 

您还可以使用 ET.tostring 代替您的 for 循环:

import xml.etree.ElementTree as ET 
 
def show_group(group,s): 
    print(s + '  len=' + str(len(group))) 
    print(ET.tostring(group)) 
 
 
def process_group(group): 
    for e in group[:]: 
        if e.tag != 'a': 
            group.remove(e) 
            show_group(group, 'removed <' + e.tag + '>') 
 
tree = ET.parse('test.xml') 
root = tree.getroot() 
 
for group in root.findall(".//group"): 
    process_group(group)