首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >ElementTree Python:如果兄弟是嵌套的,如何提取兄弟?

ElementTree Python:如果兄弟是嵌套的,如何提取兄弟?
EN

Stack Overflow用户
提问于 2019-04-08 07:53:28
回答 1查看 242关注 0票数 1

我有一个XML文件,我正尝试将其转换为Excel数据集。XML的排列方式如下:

代码语言:javascript
复制
<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的所有服务的错误代码--我不知道如何让它返回客户端实际拥有的每个服务:

代码语言:javascript
复制
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格式:

代码语言:javascript
复制
ClientID    ServiceID
01          A
01          B
01          C
02          A
02          B
02          Y
24          U

任何建议都将不胜感激!我已经查找了这一点,但只能找到显示如何提取实际兄弟项的资源--因为客户端ID和服务ID是我要提取的子项的父项,所以事实证明这有点令人困惑。谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-08 08:28:19

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

然后,您的第二个for循环可以从root.finall更改为x.findall,它将只查找当前RecordProduct元素。

例如。

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

代码语言:javascript
复制
<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

代码语言:javascript
复制
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)

打印输出

代码语言:javascript
复制
01 A
01 B
01 C
02 A
02 B
02 Y
24 U
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55564681

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档