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

时间:2016-06-30 05:15:26

标签: python xml iterator elementtree

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>

在浏览了第一个记录中的所有元素&#34; book id = bk101&#34;之后,我的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>

我删除了&#34;书籍id = bk102&#34;记录完全,但在下一个iter期间它指向书id =&#34; bk102&#34;不在etree中的元素,程序结束时不经过&#34; book id = bk103&#34;  为什么它表现得那样?

1 个答案:

答案 0 :(得分:0)

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

  

使用当前元素作为根创建树迭代器。迭代器以文档(深度优先)顺序遍历此元素及其下的所有元素。如果tag不是None或'*',则只从迭代器返回标记等于tag的元素。如果在迭代期间修改了树结构,则结果是未定义的。