ElementTree XML API 不匹配子元素

ElementTree XML API not matching subelement

我正在尝试使用 USPS API 来 return 包裹跟踪状态。我有一个方法 return 是一个 ElementTree.Element 对象,该对象是从 XML 字符串 return 从 USPS API 中构建的。

这是 returned 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)

returns:

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

returns

None

我是不是漏掉了什么?似乎我应该能够毫无问题地找到该子元素?

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