簡體   English   中英

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

[英]How to add an element to xml file by using elementtree

我有一個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()方法:

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

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

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

使用.write()方法的.write()好處是,您可以設置編碼,強制在需要時編寫XML序言,等等。

如果必須使用打開的文件來美化XML,請使用'w'模式, 'a'打開文件以進行追加,從而導致您觀察到的行為:

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

prettifyprettify的東西:

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

例如minidom美化技巧。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM