0

示例.py

import xml.etree.cElementTree as ET
log_file=open("filename.xml","a")
root = ET.Element("VOD")
doc = ET.Element("SessionDetails")
root.append(doc)
tree = ET.ElementTree(root)
tree.write("filename.xml")

o/p 运行 sample.py 3 次

<?xml version="1.0"?>

-<VOD>

<SessionDetails/>

</VOD>

[注意:我没有低于输出]所需的 o/p 是如果我运行 sample.py 3 次,o/p 应该如下

-<VOD>

<SessionDetails/>
<SessionDetails/>
<SessionDetails/>

</VOD>
4

1 回答 1

0

我使用以下方法得到了结果

第一次创建 XML

from xml.dom.minidom import getDOMImplementation
impl = getDOMImplementation()
newdoc = impl.createDocument(None, "VOD", None)
top_element = newdoc.documentElement
text = newdoc.createElement('SessionDetaild')
top_element.appendChild(text)
newdoc.writexml(open("filename.xml","w"))

用于在 xml 中附加数据

import xml.dom.minidom as m
doc = m.parse("filename.xml")
valeurs = doc.getElementsByTagName("VOD").item(0)
element = doc.createElement("SessionDetaild")
valeurs.appendChild(element)
doc.writexml(open("filename.xml","w"))

参考:

http://stackoverflow.com/questions/11074021/inserting-xml-nodes-in-an-existing-xml-document-with-python
于 2015-10-27T09:55:09.420 回答