我想有五个元素“post”的实例及其所有子元素。当我这样做时,它只会覆盖前四个并留下第 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()