繁体   English   中英

XML ElementTree Python:找到一个节点的所有关系

[英]XML ElementTree Python: Find all the relations of a node

如果我们假设以下 XML 文件:

<XML Data>
    <Record>
        <Service>
            <Product id="A"></Product>
            <Product id="B"></Product>
            <Product id="C"></Product>
        </Service>
    </Record>
    <Record>
        <Service>
            <Product id="A"></Product>
            <Product id="B"></Product>
            <Product id="Y"></Product>
        </Service>
    </Record>
    <Record>
        <Service>
            <Product id="U"></Product>
        </Service>
    </Record>
</XML Data>

如您所见,每条记录都显示一个客户,但没有唯一标识符。 每个服务都有多个产品。

我想获得与产品 A 一起销售的所有产品 因此,我试图获得这样的列表:

ServiceID
B
C
Y

我一直在使用:

import xml.etree.ElementTree as ET

根据官方文档,您可以通过[@attrib='value']基于属性的 select 元素。 在测试这个时,我用<Data></Data>交换了你的标签<XML Data></XML Data> > 。 示例代码:

from xml.etree import ElementTree as ET

data = ET.parse(r"/path/to/your/input.xml")
root = data.getroot()
for product in root.findall("./Record/Service/Product[@id='A']"):
    print(product.attrib["id"])
    print(product.text)

编辑

再次阅读您的问题后,我注意到您首先要检查服务中是否存在 ID 为 A 的产品,然后才存储 ID(唯一且已排序),因此我调整了代码:

from xml.etree import ElementTree as ET

data = ET.parse(r"/path/to/your/input.xml")
root = data.getroot()
product_ids = set()
for service in root.findall("./Record/Service"):
    list_contains_a = False

    # iterate once to identify if list contains product with ID = 'A'
    for product in service.findall("./Product"):
        if product.attrib["id"] == "A":
            list_contains_a = True

    # if list contains product with ID = 'A', iterate second time and fetch IDs
    if list_contains_a:
        for product in service.findall("./Product"):
            if product.attrib["id"] == "A":
                continue

            # add to set to prevent duplicates
            product_ids.add(product.attrib["id"])

ret_list = ["ServiceID"] + list(sorted(product_ids))
print(ret_list)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM