0

我想有五个元素“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()
4

1 回答 1

4

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

于 2012-04-24T01:46:25.407 回答