如何显示从xml转换后csv文件中的所有行

50pmv0ei  于 2022-12-15  发布在  其他
关注(0)|答案(1)|浏览(140)

我有一个使用python脚本转换为CSV文件的xml文件。转换成功,但只生成了CSV文件的最后一行。我需要一个包含xml文件中所有数据的CSV文件。
这是我用于转换的xml文件:'

<?xml version="1.0" encoding="UTF-8"?>
    <errors>
        <error id="redundantAssignment" severity="style" msg="Variable &apos;ret&apos; 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 &apos;ret&apos; 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

mkh04yzy

mkh04yzy1#

如果你试图生成一个像

这样的文件
只需更改代码的缩进并将csvfile_writer.writerow(csv_line1 + csv_line2)放入循环for location in root.iter('location')

相关问题