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