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

XML转CSV:按parent_product_id分组并汇总size与stock_quantity

解决XML转CSV并按parent_product_id分组汇总的问题

我来帮你搞定这个需求!用Python来实现XML解析、分组汇总再转CSV是非常直接的方案,下面是具体的步骤和代码示例:

实现思路

  1. 解析XML文件,提取每个product节点的字段信息
  2. 用字典按parent_product_id做分组键,同一分组内汇总size列表并累加stock_quantity
  3. 将分组后的结构化数据写入CSV文件

完整代码示例

import xml.etree.ElementTree as ET
import csv

# 1. 解析XML文件
tree = ET.parse("你的输入文件.xml")
root = tree.getroot()

# 2. 按parent_product_id分组存储数据
product_groups = {}
for product in root.findall("product"):
    # 提取字段(如果字段可能缺失,建议用findtext设置默认值)
    parent_id = product.findtext("parent_product_id", default="")
    brand_name = product.findtext("brand_name", default="")
    size = product.findtext("size", default="")
    stock_quantity = int(product.findtext("stock_quantity", default=0))

    # 分组逻辑
    if parent_id not in product_groups:
        # 首次遇到该parent_id,初始化分组数据
        product_groups[parent_id] = {
            "brand_name": brand_name,
            "sizes": [size],
            "total_stock": stock_quantity
        }
    else:
        # 已存在的parent_id,追加size并累加库存
        product_groups[parent_id]["sizes"].append(size)
        product_groups[parent_id]["total_stock"] += stock_quantity

# 3. 将分组数据写入CSV
with open("输出结果.csv", "w", newline="", encoding="utf-8") as csv_file:
    # 定义CSV表头
    fieldnames = ["parent_product_id", "brand_name", "sizes", "total_stock"]
    writer = csv.DictWriter(csv_file, fieldnames=fieldnames)

    writer.writeheader()
    # 遍历分组数据写入行
    for parent_id, group_data in product_groups.items():
        writer.writerow({
            "parent_product_id": parent_id,
            "brand_name": group_data["brand_name"],
            "sizes": ", ".join(group_data["sizes"]),  # 把size列表转为逗号分隔的字符串
            "total_stock": group_data["total_stock"]
        })

额外注意事项

  • 如果XML中存在字段缺失的情况,代码里的findtext方法已经设置了默认值,避免抛出异常
  • 要是需要对size去重,可以把追加逻辑改成sizes = list(set(group_data["sizes"] + [size])),但会打乱顺序;如果要保留顺序,可以用collections.OrderedDict来维护唯一值
  • 记得把代码里的你的输入文件.xml替换成你实际的XML文件路径,输出CSV文件名也可以按需修改

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:57:20