我正在使用从具有多个酒店位置的aN API读取的XML。每个酒店都有一个“酒店代码”元素,这是XML输出中每个酒店独有的价值,我想获得每个酒店的“纬度”和“经度”属性。我的代码现在可以解析XML并记录“纬度”和“经度”的每个实例,但没有组织为酒店的配对lat / lon,而是记录XML中的每个纬度,然后记录XML中的每个经度。我无法弄清楚怎么说:如果酒店代码==以前的酒店代码,一起记录纬度/经度; ELSE继续前往下一家酒店并记录下这家酒吧。下面是XML输出的示例部分,我的代码和代码的输出如下:
XML:
<hotel code="13272" name="Sonesta Fort Lauderdale Beach" categoryCode="4EST" categoryName="4 STARS" destinationCode="FLL" destinationName="Fort Lauderdale - Hollywood Area - FL" zoneCode="1" zoneName="Fort Lauderdale Beach Area" latitude="26.137508" longitude="-80.103438" minRate="1032.10" maxRate="1032.10" currency="USD"><rooms><room code="DBL.DX" name="DOUBLE DELUXE"><rates><rate rateKey="20161215|20161220|W|235|13272|DBL.DX|GC-ALL|RO||1~1~0||N@675BEABED1984D9E8073EB6154B41AEE" rateClass="NOR" rateType="BOOKABLE" net="1032.10" allotment="238" rateCommentsId="235|38788|431" paymentType="AT_WEB" packaging="false" boardCode="RO" boardName="ROOM ONLY" rooms="1" adults="1" children="0"><cancellationPolicies><cancellationPolicy amount="206.42" from="2016-12-11T23:59:00-05:00"/></cancellationPolicies></rate></rates></room></rooms></hotel>
CODE:
import time, hashlib
import urllib2
from xml.dom import minidom
# Your API Key and secret
apiKey =
Secret =
# Signature is generated by SHA256 (Api-Key + Secret + Timestamp (in seconds))
sigStr = "%s%s%d" % (apiKey,Secret,int(time.time()))
signature = hashlib.sha256(sigStr).hexdigest()
endpoint = "https://api.test.hotelbeds.com/hotel-api/1.0/hotels"
try:
# Create http request and add headers
req = urllib2.Request(url=endpoint)
req.add_header("X-Signature", signature)
req.add_header("Api-Key", apiKey)
req.add_header("Accept", "application/xml")
req.add_header("Content-Type", "application/xml")
req.add_data(' <availabilityRQ xmlns="http://www.hotelbeds.com/schemas/messages" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ><stay checkIn="2016-12-15" checkOut="2016-12-20"/><occupancies><occupancy rooms="1" adults="1" children="0"/></occupancies><geolocation longitude="-80.265323" latitude="26.131510" radius="10" unit="km"/></availabilityRQ>')
# Reading response and print-out
file = minidom.parse(urllib2.urlopen(req))
hotels = file.getElementsByTagName("hotel")
lat = [items.attributes['latitude'].value for items in hotels]
lon = [items.attributes['longitude'].value for items in hotels]
print lat + lon
except urllib2.HTTPError, e:
# Reading body of response
httpResonponse = e.read()
print "%s, reason: %s " % (str(e), httpResonponse)
except urllib2.URLError, e:
print "Client error: %s" % e.reason
except Exception, e:
print "General exception: %s " % str(e)
我的输出现在:
[u'26.144224',u'26.122569',u'26.11437',u'26.1243414605478',u'26.119195',u'26.1942424979814',u'26.145488',u'26.1632044819114',u'26.194145',u '26 .1457688280936',u'26.1868547339183',u'26.1037652256159',u'26.090442389015',u'26.187242',u'-80.325579',u'-80.251829',u'-80.25315',u'-80.2564349700697',你们-80.262738',u'-80.2919112076052',u'-80.258274',u'-80.2584546734579',u'-80.261252',u'-80.2576325763948',u'-80.1963213016279',u'-80.2630081633106',u'-80.2272565662588 ',u'-80.20161000000002']
答案 0 :(得分:1)
您可以将XML文件的结果放入像字典这样的可迭代结构中。 我已将您的示例xml数据放入名为hotels.xml的文件中。
from xml.dom import minidom
hotels_position = {}
dom = minidom.parse('hotels.xml')
hotels = dom.getElementsByTagName("hotel")
for hotel in hotels:
hotel_id = hotel.attributes['code'].value
position = {}
position['latitude'] = hotel.attributes['latitude'].value
position['longitude'] = hotel.attributes['longitude'].value
hotels_position[hotel_id] = position
print hotels_position
此代码输出以下结构(我添加了第二家酒店)
{u'13272': {'latitude': u'26.137508', 'longitude': u'-80.103438'}, u'13273': {'latitude': u'26.137508', 'longitude': u'-80.103438'}}
您现在可以遍历字典中的每个酒店。
for hotel in hotels_position:
print("Hotel {} is located at ({},{})".format(hotel,
hotels_position[hotel]['latitude'],
hotels_position[hotel]['latitude']))
既然您的数据处于有组织的结构中,那么您的逻辑就是&#39;写起来会容易得多。