【发布时间】: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”的情况下结束 为什么会这样?
【问题讨论】:
-
一般来说,
iterators在你修改他们正在迭代的东西时会进入非常时髦的状态......
标签: python xml iterator elementtree