将现有根目录插入现有Python ElementTree
我试图将两个现有的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)) 我明白了 如
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>'