gpt4 book ai didi

Python XML 解析

转载 作者:太空宇宙 更新时间:2023-11-04 01:24:29 25 4
gpt4 key购买 nike

我正在尝试使用 Python 解析从 OCTranspo(渥太华城市巴士公司)检索到的 XML 文件。我的问题是我似乎无法访问子字段,例如纬度和经度。

这是一个大大缩短的示例 xml 文件版本,它仍然会导致问题:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>

<Route xmlns="http://tempuri.org/">

<Trips>
<Trip><TripDestination>Barrhaven Centre</TripDestination
<TripStartTime>19:32</TripStartTime><Latitude>45.285458</Latitude
<Longitude>-75.746786</Longitude></Trip>
</Trips>

</Route>

</soap:Body>
</soap:Envelope>

这是我的代码:

import xml.etree.ElementTree as ET
import urllib

u = urllib.urlopen('https://api.octranspo1.com/v1.1/GetNextTripsForStop', 'appID=7a51d100&apiKey=5c5a8438efc643286006d82071852789&routeNo=95&stopNo=3044')
data = u.read()

f = open('route3044.xml', 'wb')
f.write(data)
f.close()

doc = ET.parse('route3044.xml')

for bus in doc.findall('Trip'):
lat = bus.findtext('Latitude')
#NEVER EXECUTES
print trip

如果我对一个非常简单的 xml 文件(没有 soap:Envelope...)执行相同的代码,那么该代码将完美运行。但是,由于我需要的 xml 是由 OCTranspo 生成的,所以我无法控制格式。

我不确定这个问题是“命名空间”问题还是 Python 中的错误。

如有任何帮助,我们将不胜感激。

更新:2013 年 9 月 21 日

我将搜索纬度和经度的代码更改为:

doc = ET.parse('Stop1A.xml')

for a in doc.findall('{http://schemas.xmlsoap.org/soap/envelope/}Body'):
for b in a.findall('{http://octranspo.com}GetNextTripsForStopResponse'):
for c in b.findall('{http://octranspo.com}GetNextTripsForStopResult'):
for d in c.findall('{http://tempuri.org/}Route'):
for e in d.findall('{http://tempuri.org/}RouteDirection'):
direction = e.findtext('{http://tempuri.org/}Direction')
if direction == 'Eastbound':
for f in e.findall('{http://tempuri.org/}Trips'):
for g in f.findall('{http://tempuri.org/}Trip'):
lat = g.findtext('{http://tempuri.org/}Latitude')
lon = g.findtext('{http://tempuri.org/}Longitude')
print lat + ',' + lon
print 'Done'

最终结果是,我现在可以在 95 号公路上看到“东行”巴士。我知道这段代码并不漂亮,但它可以工作。我的下一个目标是使用命名空间技巧进行优化。

如果有人想尝试访问该网址,请注意,通常会在 5-7 分钟内看到“没有公交车”,因为该网址只会返回离车站最近的 6 辆公交车。三辆公交车东行,三辆公交车西行。如果最近的公交车距离超过 7 分钟,则返回为空。该代码返回公交车的纬度和经度 - 然后我可以使用 Google map 绘制位置。

凯利

最佳答案

根据ElementTree documentation :

Element.findall() finds only elements with a tag which are direct children of the current element. (emphasis added)

幸运的是,ElementTree 有 XPath support

doc.findall('Trip')(搜索 doc 的直接子级)更改为 doc.findall('.//Trip')(递归搜索一个 doc 的 child ),它应该按你预期的那样工作。

关于Python XML 解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18928073/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com