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

Python嵌套XML转CSV:如何生成符合要求的DataFrame?

嵌套XML转CSV:实现订单客户信息与商品行关联

你的问题在于当前代码是单独提取每个字段并逐个添加字典,导致生成的列表里每个字典只有一个键值对,最终DataFrame每行仅含单个字段。要实现每个商品行重复对应订单、客户信息,需按XML的层级结构关联数据,核心是先提取订单级的公共信息,再遍历该订单下的所有商品,将公共信息与商品信息合并为完整记录。

修改后的代码

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

# 解析XML文件(替换为你的XML文件路径)
tree = ET.parse('your_order.xml')
root = tree.getroot()

# 定义表头
head = ['order_no', 'order_date', 'name', 'email', 'product_id', 'product_name', 'quantity']
body = []

# 遍历每个订单节点(XML结构中每个order包含订单、客户、商品信息)
for order in root.findall('.//order'):
    # 提取订单公共信息
    order_no = order.find('original-order-no').text
    order_date = order.find('order-date').text
    
    # 提取客户信息
    customer = order.find('.//customer')
    name = customer.find('.//billing-address/first-name').text
    email = customer.find('customer-email').text
    
    # 遍历当前订单下的所有商品
    for item in order.findall('.//product-lineitems/product-lineitem'):
        product_id = item.find('product-id').text
        product_name = item.find('product-name').text
        quantity = item.find('quantity').text
        
        # 合并公共信息与商品信息,添加到body
        body.append({
            'order_no': order_no,
            'order_date': order_date,
            'name': name,
            'email': email,
            'product_id': product_id,
            'product_name': product_name,
            'quantity': quantity
        })

# 转换为DataFrame并生成CSV
df = pd.DataFrame(body, columns=head)
df.to_csv('order_products.csv', index=False, sep='\t')  # sep用\t对应示例的制表符分隔,也可改为','
print(df)

代码说明

  1. 层级遍历:先定位到每个order节点,确保订单、客户、商品信息属于同一订单,避免信息错位
  2. 公共信息复用:每个订单的order_no、order_date、name、email只提取一次,然后和该订单下的每个商品信息合并
  3. 数据完整性:每条记录包含完整的订单、客户、商品信息,完全匹配你期望的CSV格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 19:50:36