I have an xml file which was converted to a CSV file using python script. The conversion was made successfully but just the last row of the CSV file was generated. I need a CSV file with all the data present in the xml file.
This is the xml file that I'm using for the conversion: `
<?xml version="1.0" encoding="UTF-8"?>
<errors>
<error id="redundantAssignment" severity="style" msg="Variable 'ret' is reassigned a value before the old one has been used.">
<location file="D:\test\main.c" line="64" column="8" info="ret is overwritten"/>
<location file="D:\test\main.c" line="62" column="8" info="ret is assigned"/>
<symbol>ret</symbol>
</error>
<error id="redundantAssignment" severity="style" msg="Variable 'ret' is reassigned a value before the old one has been used.">
<location file="D:\test\data.c" line="93" column="8" info="ret is overwritten"/>
<location file="D:\test\data.c" line="91" column="8" info="ret is assigned"/>
<symbol>ret</symbol>
</error>
</errors>
</results>
`
This is the script python that I'm runing right now :
import xml.etree.ElementTree as ET
import csv
xml_data = open('error.xml', 'r').read()
root = ET.fromstring(xml_data)
csvfile = open("data.csv",'w', newline='')
csvfile_writer = csv.writer(csvfile)
csvfile_writer.writerow(["id","severity","msg","file","line"])
for child in root.findall("errors"):
for item in child:
csv_line1 = [item.attrib["id"],item.attrib["severity"] , item.attrib["msg"]]
print(item.attrib)
#print("heeere1")
for location in root.iter('location'):
csv_line2 = [location.attrib["file"],location.attrib["line"]]
#print("heeere2")
print(location.attrib)
csvfile_writer.writerow(csv_line1 csv_line2)
csvfile.close()
And this is the output of the script :
just change the indentation of your code and put csvfile_writer.writerow(csv_line1 csv_line2)
inside this loop for location in root.iter('location')