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).
Here is how XML documents can be appended to a single master root element using minidom.
from xml.dom import minidom, getDOMImplementation
XML1 = """
<sub1>
<foo>BAR1</foo>
</sub1>"""
XML2 = """
<sub2>
<foo>BAR2</foo>
</sub2>"""
impl = getDOMImplementation()
doc = impl.createDocument(None, "root", None)
for s in [XML1, XML2]:
elem = minidom.parseString(s).firstChild
doc.firstChild.appendChild(elem)
print doc.toxml()
=>
<?xml version="1.0" ?><root><sub1>
<foo>BAR1</foo>
</sub1><sub2>
<foo>BAR2</foo>
</sub2></root>
Since appending Document
objects doesn't work, firstChild
is used to get the toplevel Element
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With