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

Python解析API返回XML时无法找到XPos标签的问题求助

解决ElementTree findall('XPos')返回空列表的问题

嘿,我看了你的代码和提供的XML结构,马上就找到问题根源了——你调用findall时用的路径不对!

问题原因分析

先拆解下你的XML层级结构:

<response>
  <header>...</header>
  <body>
    <items>
      <item>
        <XPos>129.020571507</XPos>
        <YPos>35.1464544697</YPos>
        <!-- 其他字段 -->
      </item>
    </items>
  </body>
</response>

当你用xmldata = ET.fromstring(string)后,xmldata对应的是根节点<response>。而XPos是嵌套在<body> → <items> → <item>下面的子节点,并不是<response>的直接子节点。直接调用xmldata.findall('XPos')只会查找<response>的直接子节点,自然找不到任何结果,返回空列表。

两种解决方法

方法1:按完整层级路径查找

你可以指定从根节点到XPos的相对路径,或者先定位到所有<item>节点再逐个提取字段:

# 直接定位到所有item下的XPos
xpos_nodes = xmldata.findall('./body/items/item/XPos')

# 更推荐的方式:先获取所有item节点,再遍历提取需要的字段
items = xmldata.findall('./body/items/item')
for item in items:
    x_pos = item.find('XPos').text
    y_pos = item.find('YPos').text
    hospital_name = item.find('yadmNm').text
    print(f"医院:{hospital_name} | X坐标:{x_pos} | Y坐标:{y_pos}")

方法2:递归查找所有XPos节点

如果你不需要关心XPos的父节点位置,只想提取所有XPos的值,可以用XPath的//语法递归查找所有后代节点:

# 查找XML中所有层级的XPos节点
all_xpos = xmldata.findall('.//XPos')
print(f"共找到 {len(all_xpos)} 个X坐标值:")
for node in all_xpos:
    print(node.text)

修改后的完整代码示例

from urllib.request import Request, urlopen
import xml.etree.ElementTree as ET

# 假设你的url和queryParams已经定义完成
request = Request(url + queryParams)
request.get_method = lambda: 'GET'
response = urlopen(request)
string = str(response, 'utf-8')

xmldata = ET.fromstring(string)

# 方式一:按层级提取数据
items = xmldata.findall('./body/items/item')
for item in items:
    x_pos = item.find('XPos').text
    y_pos = item.find('YPos').text
    hospital_name = item.find('yadmNm').text
    print(f"【{hospital_name}】\nX坐标:{x_pos}\nY坐标:{y_pos}\n")

# 方式二:提取所有XPos值
all_xpos = [node.text for node in xmldata.findall('.//XPos')]
print(f"所有X坐标列表:{all_xpos}")

小提示

ElementTree的findall方法遵循XPath规则:

  • 直接写节点名(如'XPos'):仅查找当前节点的直接子节点
  • ./path:从当前节点开始的相对路径
  • //node:递归查找当前节点下所有层级的node节点

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:07:39