如何使用elemen向xml文件添加元素

2024-07-05 08:02:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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()

谢谢。


Tags: 文件代码child元素parserootxmlopen
1条回答
网友
1楼 · 发布于 2024-07-05 08:02:54

您打开了要追加的文件,这会将数据添加到末尾。使用w模式打开要写入的文件。更好的方法是,在ElementTree对象上使用.write()方法:

tree = xml.parse("/tmp/" + executionID +".xml")

xmlRoot = tree.getroot()
child = xml.Element("NewNode")
xmlRoot.append(child)

tree.write("/tmp/" + executionID +".xml")

使用.write()方法还有一个额外的优点,即可以设置编码,如果需要,可以强制编写XML prolog,等等

如果必须使用打开的文件来美化XML,请使用'w'模式,'a'打开一个文件进行追加,从而导致您观察到的行为:

with open("/tmp/" + executionID +".xml", 'w') as output:
     output.write(prettify(tree))

其中prettify是沿着以下线的东西:

from xml.etree import ElementTree
from xml.dom import minidom

def prettify(elem):
    """Return a pretty-printed XML string for the Element.
    """
    rough_string = ElementTree.tostring(elem, 'utf-8')
    reparsed = minidom.parseString(rough_string)
    return reparsed.toprettyxml(indent="  ")

小人物的美化技巧。

相关问题 更多 >