【问题标题】:Add duplicate child tag in existing xml在现有 xml 中添加重复的子标签
【发布时间】:2015-10-27 02:21:36
【问题描述】:

sample.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>

【问题讨论】:

  • 好的。那么你的问题是什么?
  • 我没有得到想要的输出...

标签: python-2.7 xml.etree


【解决方案1】:

我用下面的方法得到了结果

第一次创建 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

【讨论】:

    猜你喜欢
    • 2021-03-14
    • 2022-09-24
    • 1970-01-01
    • 1970-01-01
    • 2015-02-07
    • 1970-01-01
    • 2016-09-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多