将现有根插入现有 Python ElementTree
Inserting an existing root into an existing Python ElementTree
我正在尝试 link 两个现有的 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>'
怎么样
导入 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>'
我正在尝试 link 两个现有的 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>'
怎么样
导入 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>'