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

如何用Python将特殊格式XML转CSV?遇AttributeError报错

XML属性转CSV解决方案

针对你遇到的XML属性存储数据无法用子元素查找方法转换的问题,这里提供基于Python标准库的简单解决方案,无需额外安装依赖:

示例XML结构

假设你的XML文件(比如students.xml)内容如下:

<students>
    <student name="Rick Grimes" rollnumber="1" age="15"/>
    <student name="Lori Grimes" rollnumber="2" age="16"/>
    <student name="Carl Grimes" rollnumber="3" age="14"/>
    <student name="Judith Grimes" rollnumber="4" age="13"/>
</students>

转换代码

import csv
import xml.etree.ElementTree as ET

# 解析XML文件
tree = ET.parse('students.xml')
root = tree.getroot()

# 打开CSV文件准备写入
with open('students.csv', 'w', newline='', encoding='utf-8') as csvfile:
    # 无表头版本:直接使用csv.writer写入行数据
    writer = csv.writer(csvfile)
    
    # 遍历所有student元素,提取属性值写入CSV
    for student in root.findall('student'):
        writer.writerow([
            student.attrib['name'],
            student.attrib['rollnumber'],
            student.attrib['age']
        ])

关键说明

  • 原代码报错是因为用find('name')查找子元素,但你的数据存在元素属性里,所以改用student.attrib['属性名']直接读取属性值即可
  • 运行后生成的students.csv内容完全符合你预期的格式:
    Rick Grimes,1,15
    Lori Grimes,2,16
    Carl Grimes,3,14
    Judith Grimes,4,13
    
  • 如果需要添加CSV表头,可改用csv.DictWriter实现:
    # 带表头版本的写入部分
    fieldnames = ['name', 'rollnumber', 'age']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    
    for student in root.findall('student'):
        writer.writerow({
            'name': student.attrib['name'],
            'rollnumber': student.attrib['rollnumber'],
            'age': student.attrib['age']
        })
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 20:40:46