我正在使用DB中的数据生成XML文件。 我获取的数据与此类似:
ID- 1,2,1,3
名称-A,B,C,D
年龄-20,25,20,20
当前使用以下代码:
import xml.etree.ElementTree as ET
Root=ET.Element("root")
Resultlist= <<fetching from a Database
for row in Resultlist:
Id=ET.SubElement(Root,"ID")
Id.set("id",str(row[1]))
Details=ET.SubElement(Id,"Details")
Details.set("Name",str(row[2]))
Details.set("Age",str(row[3])
我得到的输出是
<root>
<ID id="1">
<Details Age="20" Name="A" />
</ID>
<ID id="2">
<Details Age="25" Name="B" />
</ID>
<ID id="1">
<Details Age="20" Name="C" />
</ID>
<ID id="3">
<Details Age="20" Name="D" />
</ID>
</root>
我该如何修改它以获取输出,以便将具有相同ID的所有对象组合在一起?
<root>
<ID id="1">
<Details Age="20" Name="A" />
<Details Age="20" Name="C" />
</ID>
<ID id="2">
<Details Age="25" Name="B" />
</ID>
<ID id="3">
<Details Age="20" Name="D" />
</ID>
</root>
答案 0 :(得分:0)
请考虑根据您的 ResultSet 构建一个字典,其中的键是ID。然后为每个不同的ID添加其他值的嵌套循环:
Resultlist = [(1, 1, 20, "A"), (2, 2, 25, "B"), (3, 1, 20, "C"), (4, 3, 20, "D")]
# INITIALIZE DICTIONARY OF EMBEDDED LISTS
my_dict = {row[1]:[] for row in Resultlist}
# APPEND NESTED LISTS TO DICTIONARY
for row in Resultlist:
my_dict[row[1]].append([row[2], row[3]])
Root = ET.Element("root")
# ITERATE THROUGH DICTIONARY
for k, v in my_dict.items():
Id = ET.SubElement(Root, "ID")
Id.set("id", str(k))
for i in v:
Details = ET.SubElement(Id, "Details")
Details.set("Name", str(i[0]))
Details.set("Age", str(i[1]))