Reputation: 8352
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>'
Upvotes: 0
Views: 220
Reputation: 23815
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>'
Upvotes: 1
Reputation: 8352
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>'
Upvotes: 0