0

要素「post」の5つのインスタンスと、そのすべての子が必要です。このようにすると、最初の4つが上書きされ、投稿番号5が残ります。新しい要素を一意に識別する方法で追加して、スクリプトを再度実行した場合に、別のタイトルで番号1を投稿するにはどうすればよいですか。投稿番号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

1 に答える 1

4

あなたの問題はroot、ループのたびに変数を上書きし、最後のループ反復で行った作業を破棄していることです。ループの外に移動root = xml.Element(dasub)すると、期待どおりに機能します。

于 2012-04-24T01:46:25.407 に答える