2

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 >
Community
  • 1
  • 1
  • Can you please specify what exactly do you need as the output through an example maybe? – sgp Jun 23 '15 at 06:30
  • Here i have 2 records in a list but the last record is overwriting the previous added records. So i want all the 2 records to be added to the xml file. –  Jun 23 '15 at 06:36
  • It's still not clear. Edit the question. Add two things: Expected XML and Output XML with respect to the given lists. – sgp Jun 23 '15 at 06:39
  • Your expected output is not valid XML. It is missing a root element. –  Jun 23 '15 at 06:46

1 Answers1

1

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>
Kavin Eswaramoorthy
  • 1,595
  • 11
  • 19
  • I dont want to create one xml file for each record but i want to add all the records to the same xml file –  Jun 23 '15 at 09:09
  • if the first element is same in both the lists i want to add subelements of the two lists to the same element .How can i do that using python? When i am doing duplicates are getting added to the element. –  Jun 24 '15 at 11:24