将现有根目录插入现有Python ElementTree

时间:2019-03-06 13:24:05

标签: python xml elementtree

我正在尝试将两个现有的Python ElementTree对象链接在一起。

import xml.etree.ElementTree as ET

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

打印时

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

我明白了

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

如何将root2添加到root,以获得结果? `

print(ET.tostring(root))

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

2 个答案:

答案 0 :(得分:1)

怎么样

将xml.etree.ElementTree导入为ET

form.has_many :ordered_workouts, allow_destroy: true do...

输出

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

答案 1 :(得分:0)

看来,我可以使用与列表中相同的语法

root.append(root2)

print(ET.tostring(root))

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