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

Python使用ET.find、get方法获取XML值始终返回None该如何解决

Python xml.etree.ElementTree 解析XML返回None问题解决方案

核心问题根因

  • 未处理XML默认命名空间
    你提供的XML根节点定义了xmlns="http://www.ipc.com/ver10"的默认命名空间,所有子节点默认都属于该命名空间,直接传入标签名调用find()/findall()无法匹配节点,会返回None。
  • API用法错误
    get()方法的作用是获取当前节点的属性值(比如<item>标签的id属性),无法直接获取子节点的文本内容。要拿到子节点的内容,需要先定位到对应子节点,再读取节点的.text属性。

修正后可运行代码

import xml.etree.ElementTree as ET

# 先声明命名空间映射,前缀可自定义,和后续查询规则对应即可
ns = {'ipc': 'http://www.ipc.com/ver10'}

tree = ET.fromstring(res.text)
# 查询时指定命名空间前缀
types = tree.find('ipc:types', ns)
streams = tree.find('ipc:streams', ns)
item = streams.findall('ipc:item', ns)[0]

# 先定位子节点,再取text属性获取内容
name = item.find('ipc:name', ns).text
resolution = item.find('ipc:resolution', ns).text
print(name)
print(resolution)
# 如果要获取节点属性才调用get方法,比如获取item的id属性:
print(item.get('id'))
print(types, streams, item)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 14:45:08