2016-12-09 6 views
0

USPS APIを使用してパッケージ追跡のステータスを返そうとしています。 USPS APIから返されたXML文字列から構築されたElementTree.Elementオブジェクトを返すメソッドがあります。ElementTree XML APIがサブエレメントと一致しません

返されるXML文字列です。

<?xml version="1.0" encoding="UTF-8"?> 
    <TrackResponse> 
    <TrackInfo ID="EJ958088694US"> 
     <TrackSummary>The Postal Service could not locate the tracking information for your 
     request. Please verify your tracking number and try again later.</TrackSummary> 
    </TrackInfo> 
    </TrackResponse> 

私は今、私は、タグ「TrackSummary」は存在すると私はElementTreeののfindメソッドを使用していることをアクセスできるように期待することをXML文字列で見ることができますElementオブジェクト

response = xml.etree.ElementTree.fromstring(xml_str) 

にその書式を設定。

私は応答オブジェクトを繰り返し処理し、 'TrackSummary'タグが存在することを証明できます。

for item in response.iter(): 
    print(item, item.text) 

リターン:だからここ

<Element 'TrackResponse' at 0x00000000041B4B38> None 
<Element 'TrackInfo' at 0x00000000041B4AE8> None 
<Element 'TrackSummary' at 0x00000000041B4B88> The Postal Service could not locate the tracking information for your request. Please verify your tracking number and try again later. 

が問題です。

print(response.find('TrackSummary') 

戻り

None 

は、私はここで何かが足りないのですか?その子要素を問題なく見つけることができるように見えますか?

答えて

1
import xml.etree.cElementTree as ET # 15 to 20 time faster 

response = ET.fromstring(str) 

Xpath Syntax は、すべての子要素を選択します。たとえば、*/eggはeggという名前のすべての孫を選択します。

element = response.findall('*/TrackSummary') # you will get a list 
print element[0].text #fast print else iterate the list 

>>> The Postal Service could not locate the tracking informationfor your request. Please verify your tracking number and try again later. 
1

.find()メソッドは、再帰的にではなく次のレイヤーだけを検索します。再帰的に検索するには、XPathクエリを使用する必要があります。 XPathでは、二重スラッシュ//は再帰的な検索です。これを試してみてください:

# returns a list of elements with tag TrackSummary 
response.xpath('//TrackSummary') 

# returns a list of the text contained in each TrackSummary tag 
response.xpath('//TrackSummary/node()') 
関連する問題