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

使用Python解析XML转CSV:如何获取record的product-id属性?

解决XML解析中获取record的product-id属性问题

问题原因

你当前代码的错误在于,尝试从根节点myroot(对应XML中的<records>标签)获取属性,但product-id是每个<record>子节点的专属属性,而非根节点的属性。

修改后的基础代码(获取属性并打印)

import xml.etree.ElementTree as ET
mytree = ET.parse('Salesforce_01_30_2023.xml')
myroot = mytree.getroot()

for x in myroot.findall('record'):
    # 从当前遍历的record节点提取product-id属性
    product_id = x.attrib.get('product-id')
    inventory = x.find('allocation').text
    print(product_id, inventory)

扩展:生成目标CSV文件的完整代码

如果需要直接将解析结果输出为CSV,可结合Python的csv模块完成:

import xml.etree.ElementTree as ET
import csv

mytree = ET.parse('Salesforce_01_30_2023.xml')
myroot = mytree.getroot()

# 打开CSV文件并写入数据
with open('inventory_output.csv', 'w', newline='', encoding='utf-8') as csv_file:
    # 定义CSV表头
    headers = ['product-id', 'allocation']
    writer = csv.DictWriter(csv_file, fieldnames=headers)
    
    writer.writeheader()  # 写入表头行
    
    # 遍历所有record节点,提取数据并写入CSV
    for record in myroot.findall('record'):
        product_id = record.attrib.get('product-id')
        allocation = record.find('allocation').text
        writer.writerow({
            'product-id': product_id,
            'allocation': allocation
        })

补充说明

  • 使用x.attrib.get('product-id')的优势:如果某个<record>节点缺失product-id属性,代码会返回None而非抛出KeyError,鲁棒性更强。
  • 若能确保所有<record>节点都包含product-id属性,也可直接使用x.attrib['product-id']获取属性值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 07:50:30