You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现XML转CSV:如何捕获所有customfields标签数据

解决XML转CSV时多customfields标签数据丢失问题

问题分析

你的代码当前是在遍历所有customfields标签时,不断覆盖同一组变量的fieldName和value值,最后仅写入最后一次覆盖的结果。要实现每个customfields对应一行重复基础数据的需求,核心是遍历到每个customfields时就基于基础数据生成新行并写入,而非覆盖后只写一次。

假设你的XML结构类似这样

101 TEST001 UserType Admin Department Tech

现有错误代码示例(对应问题场景)

import csv
import xml.etree.ElementTree as ET

tree = ET.parse("input.xml")
root = tree.getroot()

with open("output.csv", "w", newline="", encoding="utf-8") as csv_file:
    writer = csv.writer(csv_file)
    writer.writerow(["ID", "abbreviation", "fieldName", "value"])

    for item in root.findall("item"):
        # 提取基础数据
        id_val = item.find("ID").text
        abbr_val = item.find("abbreviation").text
        # 初始化字段,最后仅保留最后一个customfields数据
        field_name = ""
        field_value = ""
        # 遍历customfields,但不断覆盖变量
        for cf in item.findall("customfields"):
            field_name = cf.find("fieldName").text
            field_value = cf.find("value").text
        # 只写入最后一次的结果
        writer.writerow([id_val, abbr_val, field_name, field_value])

修改后的正确代码

import csv
import xml.etree.ElementTree as ET

tree = ET.parse("input.xml")
root = tree.getroot()

with open("output.csv", "w", newline="", encoding="utf-8") as csv_file:
    writer = csv.writer(csv_file)
    writer.writerow(["ID", "abbreviation", "fieldName", "value"])

    for item in root.findall("item"):
        # 基础数据仅提取一次,避免重复查询XML节点
        id_val = item.find("ID").text
        abbr_val = item.find("abbreviation").text
        # 遍历每个customfields标签,每遍历一个就写入一行
        for cf in item.findall("customfields"):
            field_name = cf.find("fieldName").text
            field_value = cf.find("value").text
            # 基于基础数据+当前customfields数据生成新行
            writer.writerow([id_val, abbr_val, field_name, field_value])

关键修改点

  • 将writer.writerow()从customfields循环外移到循环内部,确保每个customfields标签对应一行输出
  • 基础数据(ID、abbreviation)仅提取一次,减少XML节点查询次数,提升效率

修改后,CSV文件中每个customfields标签都会对应一行包含重复基础数据的记录,不会再丢失前面的customfields数据。

内容的提问来源于stack exchange,提问作者gwc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 20:46:04