python 和 XML:如何将两个文档放入一个文档中
这是我的代码:
def extract_infos(i):
blabla...
blabla calculate v...
dom = xml.dom.minidom.parseString(v)
return dom
doc = xml.dom.minidom.Document()
for i in range(1,100):
dom = extract_infos(i)
for child in dom.childNodes:
doc.appendChild(child.cloneNode(True))
最后两行工作一次:
Traceback (most recent call last):
File "./c.py", line 197, in <module>
doc.appendChild(child.cloneNode(True))
File "/usr/lib/python2.6/xml/dom/minidom.py", line 1552, in appendChild
"two document elements disallowed")
xml.dom.HierarchyRequestErr: two document elements disallowed
所以我的问题是:如何将两个现有文档放入一个新文档中(将每个文档的根元素放入一个新的总体根元素中)。
Here's my code:
def extract_infos(i):
blabla...
blabla calculate v...
dom = xml.dom.minidom.parseString(v)
return dom
doc = xml.dom.minidom.Document()
for i in range(1,100):
dom = extract_infos(i)
for child in dom.childNodes:
doc.appendChild(child.cloneNode(True))
The two last lines work once then:
Traceback (most recent call last):
File "./c.py", line 197, in <module>
doc.appendChild(child.cloneNode(True))
File "/usr/lib/python2.6/xml/dom/minidom.py", line 1552, in appendChild
"two document elements disallowed")
xml.dom.HierarchyRequestErr: two document elements disallowed
So my question is: How do I place the two existing documents into a new document (placing the root elements of each into a new, overarching root element).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
以下是如何使用 minidom 将 XML 文档附加到单个主根元素。
=>
由于附加
Document
对象不起作用,因此使用firstChild
来获取顶级Element
。Here is how XML documents can be appended to a single master root element using minidom.
=>
Since appending
Document
objects doesn't work,firstChild
is used to get the toplevelElement
.问题询问如何附加一个 XML 文档到另一个,这意味着我给出了以下答案:
An XML document 必须有一个根节点,因此在生成有效的 XML 时这是不可能的。
The question asked how to append one XML document to the other, which means I gave the following answer:
An XML document must have a single root node, so this is not possible while producing valid XML.