我已经检查了这个link,但它并没有解决我的问题。
我有2个名单:
a = [['txt','stxt','pi','min','max'],['txt1','stxt1','pi1','min1','max1']]
b = [[0.45,1.23],[[0.75,1.53]]
for l1 in a:
for l2 in b:
root = ET.Element("Class ",name = l1[0])
doc = ET.SubElement(root, "subclass" , name = l1[1])
ET.SubElement(doc, l1[4], min = str(l2 [0]),max = str(l2 [1]))
tree = ET.ElementTree(root)
tree.write(FilePath)
最后一条记录将覆盖所有以前的记录。所以,如果我想将所有记录写入xml文件?我怎么能用python编程做到这一点。我还希望每个记录都以新行保存到xml文件中,但不能完全打印。
输出我需要添加到xml:
<Class name="txt"><subclass name="stxt"><pi max="1.23" min="0.45" /></subclass></Class >
<Class name="txt1"><subclass name="stxt1"><pi1 max1="1.53" min1="0.75" /></subclass></Class >
但我得到的只是xml中的一条记录:
<Class name="txt1"><subclass name="stxt1"><pi1 max1="0.1077" min1="-0.0785" /></subclass></Class >
答案 0 :(得分:0)
您每次都在写同一个文件。您需要为每个输入创建新文件,而两个for循环将使4个文件具有不需要的组合。相反,zip是你需要的
a = [['txt','stxt','pi','min','max'],['txt1','stxt1','pi1','min1','max1']]
b = [[0.45,1.23],[0.75,1.53]]
from xml.etree import ElementTree as ET
root = ET.Element("xml")
for l1 in zip(a,b):
sroot_root = ET.Element("Class ",name = l1[0][0])
doc = ET.SubElement(sroot_root, "subclass" , name = l1[0][1])
ET.SubElement(doc, l1[0][4], min = str(l1[1][0]),max = str(l1[1][1]))
root.append(sroot_root)
tree = ET.ElementTree(root)
tree.write("test.xml")
输出:
文件名: test.xml
<xml><Class name="txt"><subclass name="stxt"><max max="1.23" min="0.45" /></subclass></Class ><Class name="txt1"><subclass name="stxt1"><max1 max="1.53" min="0.75" /></subclass></Class ></xml>