ElementTree Python:如果兄弟姐妹嵌套,如何提取兄弟姐妹?

时间:2019-04-07 23:53:28

标签: xml python-3.x xml-parsing elementtree

我有一个XML文件,我正在尝试将其转换为Excel数据集。 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”是我要提取的孩子的父母,因此这更加令人困惑。谢谢!

1 个答案:

答案 0 :(得分:2)

首先选择Client,而不是先选择Record

然后可以将第二个for循环从root.finall更改为x.findall,将仅找到当前Product的{​​{1}}个元素。

示例...

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

Record

Python

<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>

打印输出

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)