0

I'm trying to link two existing Python ElementTree objects together.

import xml.etree.ElementTree as ET

root = ET.Element('Hello')
root2 = ET.Element('World')
node = ET.SubElement(root2, 'country')
node.text = 'Belgium'

When printed

print(ET.tostring(root))
print(ET.tostring(root2))

I get

b'<Hello />'
b'<World><country>Belgium</country></World>'

How do I add root2 to root, to get the result? `

print(ET.tostring(root))

b'<Hello><World><country>Belgium</country></World></Hello>'

2 Answers 2

1

How about

import xml.etree.ElementTree as ET

hello = ET.Element('Hello')
world = ET.Element('World')
hello.insert(0,world)
country = ET.SubElement(world,'Country')
country.text = 'Belgium'
print(ET.tostring(hello))

Output

b'<Hello><World><Country>Belgium</Country></World></Hello>'
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but this doesn't answer the question. "root" and "root2" are pre-existing ElementTree Objects, so the question is how to link them or how to turn a root element into a sub element late. In my real world use case, these come from different sources...
Code was modified accordingly
0

It seems, that I can use the same syntax as in lists

root.append(root2)

print(ET.tostring(root))

b'<Hello><World><country>Belgium</country></World></Hello>'

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.