Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将现有根目录插入现有Python ElementTree_Python_Xml_Elementtree - Fatal编程技术网

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

将现有根目录插入现有Python ElementTree,python,xml,elementtree,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)) 我明白了 如

我试图将两个现有的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))
我明白了

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

print(ET.tostring(root))

b'<Hello><World><country>Belgium</country></World></Hello>'
怎么样

将xml.etree.ElementTree作为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))
输出

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

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

root.append(root2)

print(ET.tostring(root))

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

谢谢,但这并不能回答问题。root和root2是预先存在的ElementTree对象,所以问题是如何链接它们,或者如何将根元素转换为子元素。在我的真实世界用例中,这些来自不同的来源……代码也相应地修改了
root.append(root2)

print(ET.tostring(root))

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