我有一个具有特殊结构的xml文件,我需要使用脚本python将其转换为csv文件这是我的xml文件的一部分:
<?xml version="1.0" encoding="UTF-8"?>
<results version="2">
<cppcheck version="2.9"/>
<errors>
<error identifier="redundantAssignment" errorStyle="style" msg="Variable 'ret' is reassigned a value before the old one has been used.">
<location file="D:testmain.c" line="64" column="8" info="ret is overwritten"/>
<location file="D:testmain.c" line="62" column="8" info="ret is assigned"/>
<symbol>ret</symbol>
</error>
<error identifier="redundantAssignment" errorStyle="style" msg="Variable 'ret' is reassigned a value before the old one has been used.">
<location file="D:testdata.c" line="93" column="8" info="ret is overwritten"/>
<location file="D:testdata.c" line="91" column="8" info="ret is assigned"/>
<symbol>ret</symbol>
</error>
</errors>
</results>
我正在使用这个脚本,但它不适合我:
import xml.etree.ElementTree as ET
import csv
# PARSE XML
xml = ET.parse("./error.xml")
root = xml.getElementsByTagName()
# CREATE CSV FILE
csvfile = open("data.csv",'w',encoding='utf-8')
csvfile_writer = csv.writer(csvfile)
# ADD THE HEADER TO CSV FILE
csvfile_writer.writerow(["identifier","file","errorStyle","msg"])
# FOR EACH EMPLOYEE
for error in root.findall("errors/error"):
if(error):
# EXTRACT EMPLOYEE DETAILS
identifier = error.get('identifier')
file = error.find('file')
errorStyle = error.find("errorStyle")
msg = error.find("msg")
csv_line = [identifier, file.text, errorStyle.text, msg.text]
# ADD A NEW ROW TO CSV FILE
csvfile_writer.writerow(csv_line)
csvfile.close()
<代码>代码>
请参考以下代码:
PP_4希望有帮助,谢谢。