Python 如何使用elementtree将元素添加到xml文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14440375/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:30:08  来源:igfitidea点击:

How to add an element to xml file by using elementtree

pythonxmlelementtree

提问by Igal

I've a xml file, and I'm trying to add additional element to it. the xml has the next structure :

我有一个 xml 文件,我正在尝试向其中添加其他元素。xml 具有下一个结构:

<root>
  <OldNode/>
</root>

What I'm looking for is :

我正在寻找的是:

<root>
  <OldNode/>
  <NewNode/>
</root>

but actually I'm getting next xml :

但实际上我得到了下一个 xml :

<root>
  <OldNode/>
</root>

<root>
  <OldNode/>
  <NewNode/>
</root>

My code looks like that :

我的代码看起来像这样:

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()

Thanks.

谢谢。

回答by Martijn Pieters

You opened the file for appending, which adds data to the end. Open the file for writing instead, using the wmode. Better still, just use the .write()method on the ElementTree object:

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

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

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

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

Using the .write()method has the added advantage that you can set the encoding, force the XML prolog to be written if you need it, etc.

使用该.write()方法还有一个额外的好处,即您可以设置编码、强制编写 XML 序言(如果需要)等。

If you mustuse an open file to prettify the XML, use the 'w'mode, 'a'opens a file for appending, leading to the behaviour you observed:

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

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

where prettifyis something along the lines of:

哪里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="  ")

e.g. the minidom prettifying trick.

例如 minidom 美化技巧。