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

如何用Python解析嵌套XML并提取指定attribute-id的元素

Python解析嵌套XML提取指定属性内容

示例XML内容

<custom-objects xmlns="http://www.demandware.com/xml/impex/customobject/2006-10-31">
<custom-object type-id="AbandonedBaskets" object-id="b4122d6090d1d6a3f8dafd34b0">
    <object-attribute attribute-id="basketJson">{"UUID":"b4122d6090d1d6a3f8dafd34b0"}</object-attribute>
    <object-attribute attribute-id="cnRelatedNo">1365</object-attribute>
    <object-attribute attribute-id="customerOwnerNo">702069175</object-attribute>
    <object-attribute attribute-id="lastModifiedBasketDate">2022-06-29T21:31:04.000+0000</object-attribute>
    <object-attribute attribute-id="natg_emailAlreadySent">true</object-attribute>
</custom-object>
</custom-objects>

方案1:使用Python内置xml.etree.ElementTree

无需额外安装依赖,直接用标准库处理:

import xml.etree.ElementTree as ET

# 匹配XML中的默认命名空间
ns = {'ns': 'http://www.demandware.com/xml/impex/customobject/2006-10-31'}

# 解析XML(如果是本地文件,替换为ET.parse('your_file.xml').getroot())
xml_content = '''上述XML字符串内容'''
root = ET.fromstring(xml_content)

# 定义需要提取的目标属性ID
target_attr_ids = ['basketJson', 'lastModifiedBasketDate']

# 循环遍历并筛选目标内容
for attr_element in root.findall('.//ns:object-attribute', ns):
    current_attr_id = attr_element.get('attribute-id')
    if current_attr_id in target_attr_ids:
        print(f"{current_attr_id}: {attr_element.text}")

方案2:使用lxml库(支持更灵活的XPath查询)

先安装依赖:pip install lxml

from lxml import etree

# 定义命名空间映射
ns = {'ns': 'http://www.demandware.com/xml/impex/customobject/2006-10-31'}

# 解析XML(本地文件用etree.parse('your_file.xml'))
xml_content = '''上述XML字符串内容'''
tree = etree.fromstring(xml_content)

# 目标属性ID列表
target_attr_ids = ['basketJson', 'lastModifiedBasketDate']

# 直接通过XPath定位并提取内容
for attr_id in target_attr_ids:
    result = tree.xpath(f'//ns:object-attribute[@attribute-id="{attr_id}"]', namespaces=ns)
    if result:
        print(f"{attr_id}: {result[0].text}")

核心注意事项

  • 命名空间必须处理:原XML包含默认命名空间,查找元素时必须指定命名空间前缀,否则无法匹配到目标节点。
  • 多节点兼容:如果XML包含多个<custom-object>节点,只需调整遍历路径为root.findall('.//ns:custom-object', ns),再在每个节点下查找对应的<object-attribute>即可。

内容的提问来源于stack exchange,提问作者Jaccon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 05:40:22