2

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?

1
  • 4
    If you have code that produces an error, please reduce that code to the shortest possible complete example that demonstrates the error. See minimal reproducible example for more information. Commented Dec 19, 2017 at 16:29

1 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.