简体   繁体   中英

Create XML file by iterating over lists in python

I have checked this link but it doesnt solved my problem.

I have 2 lists:

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)

The last record is overwriting all the previous records. So if i want all the records to be written to the xml file? how can i do that using python programming. I also want each record to be saved to the xml file in new line but not pretty printing.

Output i need to be added to the 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 >

But i am getting is only one record in xml:

<Class  name="txt1"><subclass name="stxt1"><pi1 max1="0.1077" min1="-0.0785" /></subclass></Class >

You are writing to same file every time. You need to create new file for every input and the two for loops will make 4 files with undesired combinations. Instead zip is what you need

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")

Output :

Filename: 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM