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

如何用Python将含属性的非标准XML转换为CSV?代码报错求解

非标准XML转CSV的Python解决方案

问题原因分析

你的代码报错源于两个关键错误:

  1. 目标数据是<Code>标签的属性值(而非子元素的文本内容),但你误用了.find().text方法获取,这会返回None并引发错误;
  2. rows.append()语句在循环外部,只会添加最后一条数据,无法批量处理所有<Code>元素。

修正后的代码

import xml.etree.ElementTree as Xet
import pandas as pd

cols = ["code", "displayName", "codeDescription", "isDisplayed", "displayOrder", "CodeSetName"]
rows = []

# 解析XML文件
xmlparse1 = Xet.parse("./code.xml")
root = xmlparse1.getroot()

# 遍历所有<Code>元素
for code_elem in root.findall("Code"):
    # 通过.get()方法获取元素的属性值
    row_data = {
        "code": code_elem.get("code"),
        "displayName": code_elem.get("displayName"),
        "codeDescription": code_elem.get("codeDescription"),
        "isDisplayed": code_elem.get("isDisplayed"),
        "displayOrder": code_elem.get("displayOrder"),
        "CodeSetName": code_elem.get("CodeSetName")
    }
    rows.append(row_data)

# 生成DataFrame并保存为CSV
df = pd.DataFrame(rows, columns=cols)
df.to_csv('code.csv', index=False)  # 添加index=False避免生成多余的索引列

代码说明

  • 使用root.findall("Code")精准定位所有<Code>子元素;
  • 用元素对象的.get("属性名")方法直接读取属性值,这是XML属性读取的正确方式;
  • 将rows.append()放入循环内部,确保每条<Code>数据都被添加到列表中;
  • 添加index=False参数,避免CSV文件中生成默认的索引列。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 04:15:43