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

如何使用Python ElementTree提取XML中Number节点的文本内容

问题原因

你的代码无法匹配到节点有两个核心原因:

  1. 该XML所有节点都绑定了http://schemas.microsoft.com/Contact命名空间,使用无命名空间前缀的XPath路径无法命中节点
  2. 实际节点层级是PhoneNumberCollection → PhoneNumber → Number,你写的XPath路径遗漏了中间的PhoneNumber层

可直接运行的实现代码

import xml.etree.ElementTree as ET

# 定义命名空间映射,对应XML中c前缀的绑定地址
ns_config = {'c': 'http://schemas.microsoft.com/Contact'}

tree = ET.parse('/home/user/foo.contact')
root = tree.getroot()

# 带命名空间的XPath查询,获取所有Number节点
phone_numbers = root.findall("./c:PhoneNumberCollection/c:PhoneNumber/c:Number", ns_config)
for num_node in phone_numbers:
    # 提取节点文本即为目标手机号
    print(num_node.text)

如果只需要取第一个匹配的手机号,可以简化为:

import xml.etree.ElementTree as ET
ns_config = {'c': 'http://schemas.microsoft.com/Contact'}
root = ET.parse('/home/user/foo.contact').getroot()
print(root.find("./c:PhoneNumberCollection/c:PhoneNumber/c:Number", ns_config).text)

运行后会直接输出目标值00 40 85 55。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 01:48:02