如何通过使用elementtree将元素添加到xml文件 [英] How to add an element to xml file by using elementtree

查看:191
本文介绍了如何通过使用elementtree将元素添加到xml文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

<root>
  <OldNode/>
</root>

我正在寻找的是:

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

但实际上我正在获取下一个xml:

but actually I'm getting next 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()方法:

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

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

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

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

使用 .write()方法具有的附加优点是,您可以设置编码,强制使用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.

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

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

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

其中美化的行:

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

例如小巧漂亮的花招。

这篇关于如何通过使用elementtree将元素添加到xml文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆