2012-04-24 5 views
0

私はその要素のすべてが子要素である5つのインスタンス 'post'を持っていたいと思います。私がこのようにすると、最初の4つを上書きして5番のポストを残します。新しい要素を一意に識別できるように追加するにはどうすればいいですか?スクリプトを再実行した場合、投稿番号1に上書きされますか?要素の新しいインスタンスを追加する

#!usr/bin/env python 
import xml.etree.ElementTree as xml 
#root name and name of the xml file 
dasub = 'therootname' 
#open the xml file 
file = open("/class/myname/"+dasub+".xml", 'w') 
valid = 0 
#I want 5 instances of 'post' using the number = valid to identify them 
while(valid <= 5): 
    root = xml.Element(dasub) 
    post = xml.Element('post') 
    root.append(post) 
    post.attrib['number'] = str(valid) 
    title = xml.Element('title') 
    title.text = "a diffent text for each one here" 
    post.append(title) 
    valid = valid + 1 
#write it to file 
xml.ElementTree(root).write(file) 
#close the file 
file.close() 

答えて

4

あなたの問題は、あなたが最後のループ反復で行った作業を捨て、ループをroot変数を毎回上書きされていることです。 root = xml.Element(dasub)をループの外に動かすと、期待どおりに動作します。

+0

ありがとうございました! – whuff739

関連する問題