You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python的XML ElementTree查找与产品A关联的所有产品

获取与产品A一同售出的关联产品

问题说明

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

其中每个Record对应一个客户,Service下包含该客户购买的多个Product。需要找出所有和产品A一同售出的产品,最终输出格式要求:

ServiceID
B
C
Y

已导入Python库:import xml.etree.ElementTree as ET

实现代码

方式一:解析XML字符串

如果XML数据以字符串形式存在,可使用以下代码:

import xml.etree.ElementTree as ET

# 定义XML字符串
xml_content = '''
<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>
'''

# 解析XML
root = ET.fromstring(xml_content)

# 用集合存储关联产品,自动去重
related_prods = set()

# 遍历所有客户记录
for record in root.findall('Record'):
    service_node = record.find('Service')
    # 检查当前服务是否包含产品A
    has_a = any(p.get('id') == 'A' for p in service_node.findall('Product'))
    if has_a:
        # 收集除A之外的产品ID
        for prod in service_node.findall('Product'):
            prod_id = prod.get('id')
            if prod_id != 'A':
                related_prods.add(prod_id)

# 按要求格式输出
print("ServiceID")
# 排序后输出,保证结果有序
for prod in sorted(related_prods):
    print(prod)

方式二:解析XML文件

如果XML数据存储在文件中,只需修改解析部分:

import xml.etree.ElementTree as ET

# 从文件解析XML
tree = ET.parse('your_file.xml')
root = tree.getroot()

# 后续逻辑和方式一完全一致
related_prods = set()

for record in root.findall('Record'):
    service_node = record.find('Service')
    has_a = any(p.get('id') == 'A' for p in service_node.findall('Product'))
    if has_a:
        for prod in service_node.findall('Product'):
            prod_id = prod.get('id')
            if prod_id != 'A':
                related_prods.add(prod_id)

print("ServiceID")
for prod in sorted(related_prods):
    print(prod)

代码说明

  • 使用xml.etree.ElementTree提供的API遍历XML节点,逻辑清晰高效
  • 利用集合自动去重,避免重复输出同一产品
  • 最后对结果排序,确保输出顺序和示例一致
  • 两种方式分别适配字符串和文件形式的XML数据源

内容的提问来源于stack exchange,提问作者Jon Ander Díez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 07:35:19