首页 > 解决方案 > ElementTree Python:如果兄弟姐妹嵌套,如何提取兄弟姐妹?

问题描述

我有一个要转换为 Excel 数据集的 XML 文件。XML 的排列方式如下:

<XML Data>
    <Record>
        <ID>
            <Client id="01"></Client>
        </ID>
        <Service>
            <Product id="A"></Product>
            <Product id="B"></Product>
            <Product id="C"></Product>
        </Service>
    </Record>
    <Record>
        <ID>
            <Client id="02"></Client>
        </ID>
        <Service>
            <Product id="A"></Product>
            <Product id="B"></Product>
            <Product id="Y"></Product>
        </Service>
    </Record>
    <Record>
        <ID>
            <Client id="24"></Client>
        </ID>
        <Service>
            <Product id="U"></Product>
        </Service>
    </Record>
</XML Data>

如您所见,每条记录都显示了具有多个服务的单个客户端。

我正在尝试仅使用 ElementTree 来完成这项工作。这是为每个客户端 ID 返回所有服务的错误代码——我无法弄清楚如何让它返回客户端实际拥有的每个服务:

for x in root.findall("Record/ID/Client"):
    client = x.get("id")
    for y in root.findall('.//Service/Product'):
        service = y.get("id")
        print(client, service)

我正在尝试以 CSV 格式将其安排为:

ClientID    ServiceID
01          A
01          B
01          C
02          A
02          B
02          Y
24          U

任何建议将不胜感激!我已经查找了这个,但只能找到显示如何提取实际兄弟姐妹的资源——因为客户端 ID 和服务 ID 是我想要提取的孩子的父母,这被证明有点令人困惑。谢谢!

标签: xmlpython-3.xxml-parsingelementtree

解决方案


与其先选择Client,不如先选择Record

然后你的第二个 for 循环可以从root.finallto更改为x.findall只会找到Productcurrent 的元素Record

例子...

XML 输入(test.xml;修复了无效的根元素)

<XML_Data>
    <Record>
        <ID>
            <Client id="01"></Client>
        </ID>
        <Service>
            <Product id="A"></Product>
            <Product id="B"></Product>
            <Product id="C"></Product>
        </Service>
    </Record>
    <Record>
        <ID>
            <Client id="02"></Client>
        </ID>
        <Service>
            <Product id="A"></Product>
            <Product id="B"></Product>
            <Product id="Y"></Product>
        </Service>
    </Record>
    <Record>
        <ID>
            <Client id="24"></Client>
        </ID>
        <Service>
            <Product id="U"></Product>
        </Service>
    </Record>
</XML_Data>

Python

import xml.etree.ElementTree as ET

tree = ET.parse('test.xml')

root = tree.getroot()

for x in root.findall("Record"):
    client = x.find("ID/Client").get("id")
    for y in x.findall('.//Service/Product'):
        service = y.get("id")
        print(client, service)

打印输出

01 A
01 B
01 C
02 A
02 B
02 Y
24 U

推荐阅读