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

求助:使用ElementTree解析带命名空间的XML并提取指定字段

解决ElementTree解析带命名空间XML提取字段的问题

你的XML包含两个关键命名空间:

  • soapenv: http://schemas.xmlsoap.org/soap/envelope/
  • ns1: http://schemas.cisco.com/ast/soap

ElementTree解析这类XML时,必须通过命名空间映射才能准确定位元素,下面是直接可用的实现代码:

import xml.etree.ElementTree as ET

# 解析XML文件(如果是字符串输入,改用ET.fromstring(xml_content))
tree = ET.parse('your_xml_file.xml')
root = tree.getroot()

# 定义命名空间映射字典
namespaces = {
    'soapenv': 'http://schemas.xmlsoap.org/soap/envelope/',
    'ns1': 'http://schemas.cisco.com/ast/soap'
}

# 定位到所有设备节点
device_nodes = root.findall('.//ns1:CmDevices/ns1:item', namespaces)

for node in device_nodes:
    # 提取Status字段
    status = node.find('ns1:Status', namespaces).text
    # 提取StatusReason字段
    status_reason = node.find('ns1:StatusReason', namespaces).text
    # 提取IP字段(需从IPAddress子节点下获取)
    ip_element = node.find('.//ns1:IPAddress/ns1:item/ns1:IP', namespaces)
    ip = ip_element.text

    print(f"状态: {status}")
    print(f"状态原因: {status_reason}")
    print(f"IP地址: {ip}")

核心要点:

  • 命名空间字典是关键,用它将XML中的前缀和实际URL绑定,避免重复书写长串URL
  • 使用find()/findall()时,必须传入命名空间字典参数
  • 路径中的//表示递归查找所有匹配的子元素,适配XML层级较深的结构
  • 注意字段的层级位置:Status和StatusReason直接在设备item节点下,而IP需要从IPAddress的子item中提取

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 00:30:39