Python and XML: how to put two documents in one document

Here is 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 last two lines work once:

 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 to put two existing documents in a new document (by placing the root elements of each in a new, more complete root element).

+6
source share
2 answers

Here's how XML documents can be added to a single main root element using a mini-disk.

 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 adding Document objects does not work, firstChild used to get the top level Element .

+8
source

The question was asked how to add one XML document to another, which means that I gave the following answer:

An XML document must have one root root , so this is not possible when creating valid XML.

+2
source

Source: https://habr.com/ru/post/907725/


All Articles