Robert Strauch
Robert Strauch

Reputation: 12896

Insert XML document into existing XML with Python

Given these XML documents:

Document 1

<root>
  <element1>
  </element1>
</root>

Document 2

<request>
  <dummyValue>5</dummyValue>
</request>

Using Pythons ElementTree I'd like to insert the second document into the first document so that the result would look as follows.

Resulting document

<root>
  <element1>
    <request>
      <dummyValue>5</dummyValue>
    </request>
  </element1>
</root>

ET.SubElement(element1, request) gives me a serialization error.

Is there a Pythonic way of doing this?

Upvotes: 2

Views: 2396

Answers (1)

Robᵩ
Robᵩ

Reputation: 168626

SubElement() constructs an Element and then attaches it to the tree. Since you already have request as an Element, you don't need to construct a new one.

Try element1.append(request), like so:

import xml.etree.ElementTree as ET

doc1 = ET.XML('''
<root>
  <element1>
  </element1>
</root>
''')

request = ET.XML('''
<request>
  <dummyValue>5</dummyValue>
</request>
''')

for element1 in doc1.findall('element1'):
    element1.append(request)

ET.dump(doc1)

Upvotes: 4

Related Questions