如何使用Python ElementTree提取XML中Number节点的文本内容
问题原因
你的代码无法匹配到节点有两个核心原因:
- 该XML所有节点都绑定了
http://schemas.microsoft.com/Contact命名空间,使用无命名空间前缀的XPath路径无法命中节点 - 实际节点层级是
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
相关产品推荐
相关产品推荐

