2016-06-30 8 views
0

iter()関数は、以前の反復でetreeから削除した要素を指しています。なぜiter()が新しい値で更新されないのですか?コードに何か問題がありますか? HERESにコードiter()がpythonのetree要素の新しい値で更新されていないのはなぜですか?

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> 

"書籍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ではbook id = "bk102"要素はetreeにはなく、プログラムは "book id = bk103"を経由せずに終了します なぜそれがそのように動作していますか?

+0

一般 – mgilson

+0

関連...あなたは、彼らはそれを反復しているとして、彼らは反復処理しているという事を変更するときiterators'が本当にファンキーな状態に取得することができます '、スピーキング:http://stackoverflow.com/a/38003580/748858 – mgilson

+0

可能な偽薬ですか? http://stackoverflow.com/q/37702011/748858 – mgilson

答えて

0

iter() documentation明示的挙動はツリーが変更されたときに定義されていないことを述べて:

ルートとして現在の要素を持つツリーのイテレータを作成します。イテレーターは、この要素とその下のすべての要素を、文書(深度優先)順に反復処理します。 tagがNoneまたは '*'でなければ、タグがタグと等しい要素だけがイテレータから返されます。繰り返し中にツリー構造が変更された場合、結果は未定義です。

関連する問題