【问题标题】:ElementTree XML API not matching subelementElementTree XML API 不匹配子元素
【发布时间】: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


    【解决方案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.
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-11-15
        • 2015-05-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-30
        • 2018-08-27
        相关资源
        最近更新 更多