You need to enable JavaScript to run this app. 如何使用Python ElementTree提取XML中指定Item key对应的value值
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python ElementTree提取XML中指定Item key对应的value值

解决方案

核心问题说明

  • 你编写的XPath表达式语法不符合ElementTree规范,属性筛选需写在节点后的方括号内
  • return (<SupportingData>节点带有命名空间`http://EMVS.EU/Common/20181/`,直接写节点名无法命中目标节点
    )

可运行完整代码

import xml.etree.ElementTree as ET                                                        
import os                                                                                 

# 定义命名空间映射,和XML里的命名空间对应
NS = {
    'emvs': 'http://EMVS.EU/Common/20181/'
}

def get_item_value(root, key_name):
    # 按key属性筛选Item节点,取对应value值
    xpath = f".//emvs:SupportingData/emvs:Item[@key='{key_name}']"
    item = root.find(xpath, namespaces=NS)
    return item.attrib['value'] if item is not None else None

if __name__ == '__main__':
    xmlfile = 'xmltest.xml'                                                              
    fullfile = os.path.abspath(os.path.join('filer', xmlfile))                                
    tree = ET.parse(fullfile)                                                                 
    root = tree.getroot()                                                                     

    # 示例:提取指定key的value
    error_code = get_item_value(root, 'errorcode')
    date = get_item_value(root, 'date')
    product_code = get_item_value(root, 'productcode')

    print(f"错误码:{error_code}")
    print(f"日期:{date}")
    print(f"产品编码:{product_code}")

代码说明

  1. 首先定义命名空间映射NS,对应节点的xmlns属性值,XPath中用前缀emvs代替完整命名空间地址
  2. 封装的get_item_value函数可直接传入要查询的key名(如errorcode、date),自动返回对应的value值,适配你批量处理不同key的需求
  3. 若查询的key不存在,函数会返回None,避免运行报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 05:54:03