0

I am working on a project where it's required xml files to be generated. I made a code to perform the xml but I am facing an issue with my output. I am trying to iterate through csv file and convert it to xml

my code

import pandas as pd
from itertools import zip_longest
from xml.etree.ElementTree import ElementTree
from xml.etree.ElementTree import Element, SubElement, tostring
import xml.etree.ElementTree as etree
import os
df= pd.read_csv('detector.csv')
df.head()

df1= df['id'].astype(str)
df2=df['lane'].astype(str)
df3=df['pos'].astype(str)
df4=df['freq'].astype(str)
df5=df['file'].astype(str)

df_all= list(zip_longest(df1, df2, df3, df4, df5))

for i, j, k, l, m in df_all:
    root=Element('additional')
    tree=ElementTree(root)
    child= SubElement(root, 'e1Detector')
    child.set('id', i)
    child.set('lane', j)
    child.set('pos', k)
    child.set('freq', l)
    child.set('file', m)
   
    print(etree.tostring(root))
    tree.write('detector.add.xml')

what I get is only the last line of my csv file.

<additional>
<e1Detector id="e1Detector_77317_2_5" lane="77317_2" pos="1.51" freq="900.0" file="e1Detector_77317_2_5.xml" />
</additional>

what I want is this

<additional>
<e1Detector id="e1Detector_77305_1_1" lane="77305_1" pos="11.11" freq="900.0" file="e1Detector_77305_1_1.xml" />
<e1Detector id="e1Detector_77305_2_2" lane="77305_2" pos="11.11" freq="900.0" file="e1Detector_77305_2_2.xml" />
<e1Detector id="e1Detector_77317_0_3" lane="77317_0" pos="2.99" freq="900.0" file="e1Detector_77317_0_3.xml" />
<e1Detector id="e1Detector_77317_1_4" lane="77317_1" pos="2.06" freq="900.0" file="e1Detector_77317_1_4.xml" />
<e1Detector id="e1Detector_77317_2_5" lane="77317_2" pos="1.51" freq="900.0" file="e1Detector_77317_2_5.xml" />
</additional>

I tried using append but it didn't work

you can find my csv file here

James Z
  • 12,209
  • 10
  • 24
  • 44
waed1110
  • 13
  • 3

1 Answers1

0

you need to move the tree and root elements out of the loop, aswell as writing the file:

root=Element('additional')
tree=ElementTree(root)

for i, j, k, l, m in df_all:
    child= SubElement(root, 'e1Detector')
    child.set('id', i)
    child.set('lane', j)
    child.set('pos', k)
    child.set('freq', l)
    child.set('file', m)

print(etree.tostring(root))
tree.write('detector.add.xml')

otherwise you just overwrite the file with each run of the loop.

Mr.Manhattan
  • 5,315
  • 3
  • 22
  • 34
  • thanks man, that worked. one more question please, how to make new line after each iteration? – waed1110 Mar 03 '21 at 12:05
  • @waed1110 maybe https://stackoverflow.com/questions/28813876/how-do-i-get-pythons-elementtree-to-pretty-print-to-an-xml-file could help you there. – Mr.Manhattan Mar 03 '21 at 13:00
  • thank you very much, I appreciate your help. I am new to programming and your contribution helped me and saved lots of time for me. thanks again – waed1110 Mar 03 '21 at 13:18