Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python and XML: how to place two documents into a single document

Tags:

python

dom

xml

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

like image 629
Olivier Pons Avatar asked Feb 05 '12 22:02

Olivier Pons


2 Answers

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.

like image 118
mzjn Avatar answered Nov 03 '22 01:11

mzjn


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.

like image 23
Gareth Latty Avatar answered Nov 03 '22 02:11

Gareth Latty