XML转CSV仅生成最后一行,如何导出XML全量数据至CSV
XML转CSV仅导出最后一行的问题修复
问题根源
- 遍历范围错误:原脚本用
root.iter('location')遍历整个XML的所有<location>节点,而非当前<error>节点下的子节点,导致每次循环都会覆盖csv_line2变量,最终只保留最后一个<location>的数据。 - 写入时机错误:
writerow语句的缩进位置错误,放在了<error>节点循环的外部,整个循环结束后仅执行一次写入操作,自然只输出最后一行数据。
修正后的Python脚本
import xml.etree.ElementTree as ET import csv # 读取并解析XML文件 tree = ET.parse('error.xml') root = tree.getroot() # 打开CSV文件准备写入(用with自动管理文件资源) with open("data.csv", 'w', newline='', encoding='utf-8') as csvfile: csv_writer = csv.writer(csvfile) # 写入CSV表头 csv_writer.writerow(["id", "severity", "msg", "file", "line"]) # 遍历errors节点下的每个error子节点 for error in root.find('errors').findall('error'): # 提取error节点的核心属性 error_base = [error.attrib["id"], error.attrib["severity"], error.attrib["msg"]] # 遍历当前error节点下的所有location子节点 for location in error.findall('location'): # 提取location节点的文件和行号信息 location_info = [location.attrib["file"], location.attrib["line"]] # 合并数据并写入CSV行 csv_writer.writerow(error_base + location_info)
关键修正说明
- 缩小遍历范围:将全局遍历
root.iter('location')改为针对当前<error>节点的error.findall('location'),确保每个<error>的位置信息被正确关联。 - 调整写入逻辑:把
writerow移到<location>循环内部,每个位置信息对应一条CSV记录,保证所有数据都被写入。 - 优化文件操作:使用
with上下文管理器处理文件,无需手动调用close(),避免资源泄漏。 - 编码规范:指定CSV文件编码为
utf-8,避免特殊字符(如XML中的'转义字符)出现乱码。
内容的提问来源于stack exchange,提问作者monaco Stephen
相关产品推荐
相关产品推荐

