简体   繁体   中英

Inserting an existing root into an existing Python ElementTree

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>'

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>'

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>'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM