【问题标题】:why iter() is not getting updated with new value of etree elements in python?为什么 iter() 没有在 python 中使用 etree 元素的新值进行更新?
【发布时间】:2016-06-30 05:15:26
【问题描述】:

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”记录,但是在下一次迭代中,它指向不在 etree 中的 book id="bk102" 元素,并且程序在没有经过“book id=bk103”的情况下结束 为什么会这样?

【问题讨论】:

标签: python xml iterator elementtree


【解决方案1】:

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

创建一个以当前元素为根的树迭代器。迭代器按文档(深度优先)顺序迭代此元素及其下方的所有元素。如果 tag 不是 None 或 '*',则迭代器只返回 tag 等于 tag 的元素。如果在迭代过程中修改了树结构,结果是不确定的。

【讨论】:

    猜你喜欢
    • 2012-02-28
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 2012-10-17
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    相关资源
    最近更新 更多