我只想用列表中的元素制作一个XML,但似乎工作得很糟糕,制作一个空白的XML我需要帮助
import xml.etree.cElementTree as ET
lista = [1,2,3,4,5,6,7,"final"]
for i in range(len(lista)):
if i == 0 :
root = ET.Element("{}".format(lista[i]))
else:
doc = ET.SubElement(root, "doc")
nodo1 = ET.SubElement(doc, "nodo")
ET.SubElement(doc, "nodo")
arbol = ET.ElementTree(root)
arbol.write("path")
答案 0 :(得分:0)
根据您的评论,您可以通过以下方式实现以下目标:
import xml.etree.cElementTree as ET
lista = [1,2,3,4,5,6,7,"final"]
for i in range(len(lista)):
# set up a specific attribute based on the content of lista
attrib = dict(lista=str(lista[i]))
if i == 0 :
root = ET.Element("{}".format(lista[i]), attrib)
prior = root
else:
prior = ET.SubElement(prior, "doc", attrib)
ET.SubElement(prior, "nodo")
ET.SubElement(prior, "nodo")
arbol = ET.ElementTree(root)
arbol.write('./result.xml')
诀窍是将最后一次迭代的子元素存储在先前,将下一个子元素创建为先前的子元素,然后再次将此元素设置为先前。
为result.xml:
<1 lista="1">
<doc lista="2">
<doc lista="3">
<doc lista="4">
<doc lista="5">
<doc lista="6">
<doc lista="7">
<doc lista="final">
<nodo />
<nodo />
</doc>
</doc>
</doc>
</doc>
</doc>
</doc>
</doc>
</1>