要素「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()