为什么 iter() 没有更新 python 中 etree 元素的新值?

why iter() is not getting updated with new value of etree elements in python?

iter() 函数指向我在上一次迭代期间从 etree 中删除的元素,为什么 iter() 没有更新为新值?代码有什么问题吗?这是代码

root = etree.parse(open("Sample.xml",'r'))
for e in root.iter():
    print etree.tostring(e)
    b=root.getpath(e)
    for bad in root.xpath(b):
        if(some condition):
            bad.getparent().remove(bad)#removing some elements in etree which are yet to come in the iter()
    print etree.tostring(root, pretty_print=True, xml_declaration=True)

我的XMl输入:

<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications 
      with XML.</description>
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>A former architect battles corporate zombies, 
      an evil sorceress, and her own childhood to become queen 
      of the world.</description>
   </book>
   <book id="bk103">
      <author>fgh<a1>ss</a1><a2>dd</a2></author>
      <title>Oberon's Legacy</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2001-03-10</publish_date>
      <description>In post-apocalypse England, the mysterious 
      agent known only as Oberon helps to create a new life 
      for the inhabitants of London. Sequel to Maeve 
      Ascendant.</description>
   </book>
</catalog>

遍历 "book id=bk101" 的第一条记录中的所有元素后,我的 etree 更新为

<?xml version='1.0' encoding='ASCII'?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications 
      with XML.</description>
   </book>
   <book id="bk103">
      <author>fgh<a1>ss</a1><a2>dd</a2></author>
      </book>
   </catalog>

那是我完全删除了 "book id=bk102" 记录,但是在下一个 iter 期间它指向不在 etree 中的书 id="bk102" 元素,程序结束时没有经过 "book id=bk103" 为什么会这样?

iter() documentation 明确指出修改树时行为未定义:

Creates a tree iterator with the current element as the root. The iterator iterates over this element and all elements below it, in document (depth first) order. If tag is not None or '*', only elements whose tag equals tag are returned from the iterator. If the tree structure is modified during iteration, the result is undefined.