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

如何用Python以postal_code为键解析XML并提取11211字符串?

提取XML中的postal_code值

嘿,这事儿不难!我给你用Python的内置XML解析模块来实现,不需要装额外依赖,简单直接。

方法一:遍历节点查找(逻辑清晰,适合新手理解)

import xml.etree.ElementTree as ET

# 你的XML内容
xml_content = '''<GeocodeResponse> 
<status>OK</status> 
<result> 
<type>street_address</type> 
<formatted_address>277 Bedford Ave, Brooklyn, NY 11211, USA</formatted_address> 
<address_component> 
<long_name>277</long_name> 
<short_name>277</short_name> 
<type>street_number</type> 
</address_component> 
<address_component> 
<long_name>Bedford Avenue</long_name> 
<short_name>Bedford Ave</short_name> 
<type>route</type> 
</address_component> 
<address_component> 
<long_name>Williamsburg</long_name> 
<short_name>Williamsburg</short_name> 
<type>neighborhood</type> 
<type>political</type> 
</address_component> 
<address_component> 
<long_name>11211</long_name> 
<short_name>11211</short_name> 
<type>postal_code</type> 
</address_component>
</result>
</GeocodeResponse>'''

# 解析XML字符串
root = ET.fromstring(xml_content)

# 遍历所有address_component节点
for addr_comp in root.findall('.//address_component'):
    # 收集当前节点下的所有type标签文本
    component_types = [type_elem.text for type_elem in addr_comp.findall('type')]
    # 判断是否包含postal_code类型
    if 'postal_code' in component_types:
        # 提取邮编(这里long_name和short_name值相同,选哪个都行)
        postal_code = addr_comp.find('long_name').text
        print(postal_code)  # 输出: 11211
        # 如果是在函数中使用,直接return postal_code即可

方法二:用XPath直接定位(更紧凑高效)

如果你熟悉XPath语法,可以一步到位,代码更简洁:

import xml.etree.ElementTree as ET

xml_content = '''[此处可复用上面的XML内容]'''

root = ET.fromstring(xml_content)

# 用XPath直接筛选出包含postal_code类型的节点,再提取对应值
postal_code = root.find('.//address_component[type="postal_code"]/long_name').text
print(postal_code)  # 输出: 11211

补充说明

  • 两种方法最终都会返回字符串类型的11211,完全满足你的需求;
  • 如果你的XML是从本地文件读取的,把ET.fromstring(xml_content)替换成tree = ET.parse('你的文件名.xml'); root = tree.getroot()即可;
  • 因为目标节点的long_name和short_name值完全一致,所以选哪个标签提取都没问题,可根据实际场景调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:22:11