Iga*_*gal 7 python xml elementtree
我有一个xml文件,我正在尝试添加其他元素.xml具有下一个结构:
<root>
<OldNode/>
</root>
Run Code Online (Sandbox Code Playgroud)
我正在寻找的是:
<root>
<OldNode/>
<NewNode/>
</root>
Run Code Online (Sandbox Code Playgroud)
但实际上我正在接下来的xml:
<root>
<OldNode/>
</root>
<root>
<OldNode/>
<NewNode/>
</root>
Run Code Online (Sandbox Code Playgroud)
我的代码看起来像这样:
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()
Run Code Online (Sandbox Code Playgroud)
谢谢.
Mar*_*ers 10
您打开了要追加的文件,这会将数据添加到最后.使用该w
模式打开文件进行写入.更好的是,只需.write()
在ElementTree对象上使用该方法:
tree = xml.parse("/tmp/" + executionID +".xml")
xmlRoot = tree.getroot()
child = xml.Element("NewNode")
xmlRoot.append(child)
tree.write("/tmp/" + executionID +".xml")
Run Code Online (Sandbox Code Playgroud)
使用该.write()
方法的另一个好处是,您可以设置编码,强制在需要时编写XML prolog等.
如果必须使用打开的文件来美化XML,请使用'w'
模式,'a'
打开文件以进行追加,从而导致您观察到的行为:
with open("/tmp/" + executionID +".xml", 'w') as output:
output.write(prettify(tree))
Run Code Online (Sandbox Code Playgroud)
以下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=" ")
Run Code Online (Sandbox Code Playgroud)
例如minidom美化技巧.