2016-12-09 1 views
0

Я пытаюсь использовать API USPS для возврата статуса отслеживания пакетов. У меня есть метод, который возвращает объект ElementTree.Element, построенный из строки XML, возвращаемой из API USPS.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> 

Я форматировать, что в объект Element

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

Теперь я могу видеть в строке XML, что тег «TrackSummary» существует, и я бы ожидать, чтобы быть в состоянии получить доступ, что с помощью метода найти ElementTree в ,

В качестве дополнительного доказательства я могу перебирать объект ответа и доказывать, что существует тег '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 выбирает всех внуков по имени яйцо.

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()')