在用Python标准库xml.etree.ElementTree解析XML时,如果文档带有命名空间,使用findall方法直接写本地标签名往往返回空列表。这是因为带命名空间的节点完整标签其实是“命名空间URI加本地名”,只有按规则声明映射关系才能正确查找。

什么是XML命名空间
XML命名空间用来避免不同来源标签重名。文档顶部通常这样写:
<root xmlns:ns="http://ippipp.com/ns"> <ns:item>值1</ns:item> <ns:item>值2</ns:item> </root>
这里ns是前缀,http://ippipp.com/ns是命名空间URI。实际节点名称为带URI的限定名。
常见错误写法
不少人会这样写代码,结果查不到:
import xml.etree.ElementTree as ET
tree = ET.parse('data.xml')
root = tree.getroot()
# 错误:没有处理命名空间
items = root.findall('item')
print(items) # 输出 []
正确使用findall带命名空间查找
需要构造一个映射字典,并在查找路径中用前缀表示命名空间:
import xml.etree.ElementTree as ET
tree = ET.parse('data.xml')
root = tree.getroot()
# 声明命名空间映射
ns = {'ns': 'http://ippipp.com/ns'}
# 使用前缀ns写路径
items = root.findall('ns:item', ns)
for it in items:
print(it.text)
findall第一个参数是带前缀的XPath式路径,第二个参数就是命名空间map。只要前缀和URI对应,就能查到节点。
从文档自动读取命名空间
如果不知道URI,可以通过标签的字典键提取:
import xml.etree.ElementTree as ET
tree = ET.parse('data.xml')
root = tree.getroot()
# root.tag类似 '{http://ippipp.com/ns}root'
uri = root.tag.split('}')[0].strip('{')
ns = {'ns': uri}
items = root.findall('ns:item', ns)
查找多层嵌套节点
若item在子元素内,路径可写为:
# 假设结构为 root -> body -> ns:item
nodes = root.findall('ns:body/ns:item', ns)
| 场景 | 写法要点 |
|---|---|
| 已知URI | 手动写ns map |
| 未知URI | 从root.tag解析 |
| 多层路径 | 用斜杠连接带前缀标签 |
小结
处理带命名空间的XML,核心就是给findall传命名空间映射,路径里用前缀代替真实URI。掌握这个方法,就能稳定解析各类标准XML数据。
Pythonxml_etree_ElementTreefindall_namespace修改时间:2026-07-28 10:27:19