我想创建一个xml文件,如下所示,有几个subElements与Parent Element同名。
我编写的代码如下:
import xml.etree.ElementTree as ET
TEST2 = ET.Element("TEST2")
GROUP=ET.SubElement(TEST2,'GROUP')
GROUP.set('id','1')
GROUP=ET.SubElement(GROUP,'GROUP')
GROUP.set('id','1_1')
GROUP=ET.SubElement(GROUP,'GROUP')
GROUP.set('id','1_2')
GROUP=ET.SubElement(GROUP,'GROUP')
GROUP.set('id','1_3')
GROUP=ET.SubElement(TEST2,'GROUP')
GROUP.set('id','2')
GROUP=ET.SubElement(GROUP,'GROUP')
GROUP.set('id','2_1')
GROUP=ET.SubElement(GROUP,'GROUP')
GROUP.set('id','2_2')
GROUP=ET.SubElement(GROUP,'GROUP')
GROUP.set('id','3_3')
tree = ET.ElementTree(TEST2)
tree.write("TEST2.xml")
结果xml是这样的,这是错误的。
答案 0 :(得分:0)
您使用任何新GROUP
覆盖SubElement
更改为以下内容:
GROUP=ET.SubElement(TEST2,'GROUP')
GROUP.set('id','1')
sub_GROUP=ET.SubElement(GROUP,'GROUP')
sub_GROUP.set('id','1_1')
... an so on