添加元素的新实例

时间:2012-04-24 01:20:32

标签: python xml instance

我希望有五个元素'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()

1 个答案:

答案 0 :(得分:4)

你的问题是你每次循环都会覆盖root变量,丢掉你在上一次循环迭代中所做的工作。将root = xml.Element(dasub)向上移出循环,它将按预期工作。