我有一个xml文件,我正在尝试向其中添加其他元素。 xml具有下一个结构:
<root>
<OldNode/>
</root>
我要找的是:
<root>
<OldNode/>
<NewNode/>
</root>
但实际上我得到了下一个xml:
<root>
<OldNode/>
</root>
<root>
<OldNode/>
<NewNode/>
</root>
我的代码是这样的:
file = open("/tmp/" + executionID +".xml", 'a')
xmlRoot = xml.parse("/tmp/" + executionID +".xml").getroot()
child = xml.Element("NewNode")
xmlRoot.append(child)
xml.ElementTree(root).write(file)
file.close()
谢谢。
您打开了要追加的文件,这会将数据添加到末尾。使用
w
模式打开要写入的文件。更好的方法是,在ElementTree对象上使用.write()
方法:使用
.write()
方法还有一个额外的优点,即可以设置编码,如果需要,可以强制编写XML prolog,等等如果必须使用打开的文件来美化XML,请使用
'w'
模式,'a'
打开一个文件进行追加,从而导致您观察到的行为:其中
prettify
是沿着以下线的东西:小人物的美化技巧。
相关问题 更多 >
编程相关推荐