How to add an element to xml file by using elementtree

点点圈 提交于 2019-11-30 04:18:35

问题


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

<root>
  <OldNode/>
</root>

What I'm looking for is :

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

but actually I'm getting next 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.


回答1:


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

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.

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

where prettify is something along the lines of:

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.



来源:https://stackoverflow.com/questions/14440375/how-to-add-an-element-to-xml-file-by-using-elementtree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!