我有一个使用python脚本转换为CSV文件的xml文件。转换成功,但只生成了CSV文件的最后一行。我需要一个包含xml文件中所有数据的CSV文件。
这是我用于转换的xml文件:'
<?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>
'
这是我正在运行的脚本python:
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()
下面是脚本的输出:enter image description here
1条答案
按热度按时间mkh04yzy1#
如果你试图生成一个像
这样的文件
只需更改代码的缩进并将
csvfile_writer.writerow(csv_line1 + csv_line2)
放入循环for location in root.iter('location')
中