【发布时间】:2016-12-09 16:29:17
【问题描述】:
我正在尝试使用 USPS API 返回包裹跟踪的状态。我有一个方法,它返回一个 ElementTree.Element 对象,该对象是从 USPS API 返回的 XML 字符串构建的。
这是返回的 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>
我把它格式化成一个元素对象
response = xml.etree.ElementTree.fromstring(xml_str)
现在我可以在 xml 字符串中看到标签“TrackSummary”存在,我希望能够使用 ElementTree 的 find 方法访问它。
作为额外的证据,我可以遍历响应对象并证明“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
我在这里遗漏了什么吗?似乎我应该能够毫无问题地找到那个子元素?
【问题讨论】:
标签: python xml parsing elementtree