2016-10-12 4 views
1

私はいくつかのホテルの場所を持つAPIからXMLを読み込んで作業しています。各ホテルには、XML出力の各ホテル固有の値である「ホテルコード」要素があり、ホテルごとに「緯度」属性と「経度」属性を取得したいと考えています。私のコードは今XMLを解析し、 "緯度"と "経度"の各インスタンスを記録できますが、ホテルの緯度/経度のペアとして編成されるのではなく、XMLの各緯度とXMLのすべての経度を記録します。私は、ホテルのコード==前のホテルコード、記録緯度/経度を一緒に言う方法を考え出すのに困っている。 ELSEは次のホテルに移動し、その緯度/経度を記録します。XML内の要素を反復処理し、サブ要素の値を取得するPythonループ

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||[email protected]" 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:RIGHT NOW

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) 

MY OUTPUT:

[私のコードと私のコードの出力であるとして、XML出力の例セクションには、以下の通りです「26.144254」、「26.122569」、26'11437''26'243414605478 '、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.090 「u'-80.225729」、「u'-80.251829」、「u'-80.25315」、「u'-80.2564349700697」、「u'-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' ]

答えて

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 

このコードは、次の構造(私は2番目のホテルを追加しました)

{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'])) 

データが整理された構造になっているので、 '論理'ははるかに簡単に書くことができます。

+0

ありがとうScotty!あなたのソリューションはうまくいくと思います。結果を.xmlファイルに配置するのではなく、実際には –

+0

を使用してAPIリクエスト出力から直接読み取ることができました申し訳ありませんが、誤ってEnterキーを押しました...とにかく、ファイル= minidom.parse urllib2.urlopen(req))hotels =データを解析して辞書を構築するためのfile.getElementsByTagName( "hotel")。このコードは、実行するたびにAPIリクエストを行います。あなたの助けをもう一度ありがとう –

+0

素晴らしい。 APIへのアクセス権がないため、私はデータをファイルに格納していませんでした。それはあなたのためにうれしいです。 – scotty3785

関連する問題