【问题标题】:Parsing XML attributes with nested namespaces with lxml使用 lxml 解析带有嵌套命名空间的 XML 属性
【发布时间】:2015-07-06 12:58:38
【问题描述】:

我想解析 RankByCountry 中的国家代码属性。我该怎么做?

表示-打印一个列表 ['GB', 'US', 'O']

<aws:UrlInfoResponse xmlns:aws="http://alexa.amazonaws.com/doc/2005-10-05/"><aws:Response xmlns:aws="http://awis.amazonaws.com/doc/2005-07-11"><aws:OperationRequest><aws:RequestId>122bfdc6-ae8e-d2a2-580e-3841ab33b966</aws:RequestId></aws:OperationRequest><aws:UrlInfoResult><aws:Alexa>
 <aws:TrafficData>
  <aws:DataUrl type="canonical">androidjones.com/</aws:DataUrl>
  <aws:RankByCountry>
    <aws:Country Code="GB">
      <aws:Rank>80725</aws:Rank>
      <aws:Contribution>
        <aws:PageViews>30.6%</aws:PageViews>
        <aws:Users>41.3%</aws:Users>
      </aws:Contribution>
    </aws:Country>
    <aws:Country Code="US">
      <aws:Rank>354356</aws:Rank>
      <aws:Contribution>
        <aws:PageViews>39.1%</aws:PageViews>
        <aws:Users>28.9%</aws:Users>
      </aws:Contribution>
    </aws:Country>
    <aws:Country Code="O">
      <aws:Rank/>
      <aws:Contribution>
        <aws:PageViews>30.2%</aws:PageViews>
        <aws:Users>29.8%</aws:Users>
      </aws:Contribution>
    </aws:Country>
  </aws:RankByCountry>
 </aws:TrafficData>
</aws:Alexa></aws:UrlInfoResult><aws:ResponseStatus xmlns:aws="http://alexa.amazonaws.com/doc/2005-10-05/"><aws:StatusCode>Success</aws:StatusCode></aws:ResponseStatus></aws:Response></aws:UrlInfoResponse>

已经试过了——

namespaces = {"aws": "http://awis.amazonaws.com/doc/2005-07-11"}
RankByCountry = tree.xpath("//aws:Country/Code", namespaces=namespaces)

但没有运气。

还有:

for country in tree.xpath('//Country'):
   for attrib in country.attrib:
      print '@' + attrib + '=' + country.attrib[attrib]

【问题讨论】:

  • 你试过了吗?
  • 是的,但不知道如何访问属性,只是数据...
  • @KhalilAmmour-خليلعمور - 我编辑了这个问题。
  • 我的错我以为你的意思是使用regex !!

标签: python xml xml-parsing lxml alexa


【解决方案1】:

该文档看起来很奇怪,因为它使用了两次 aws 命名空间前缀。您需要使用更具体的命名空间,因为这会覆盖带有前缀aws 的全局命名空间。其实你这样做是对的。

问题出在 xpath 表达式本身,它应该是这样的:

for country in tree.xpath('//aws:RankByCountry/aws:Country/@Code', namespaces=namespaces):
    print(country) 

注意&lt;aws:RankByCountry&gt; 没有Code 属性,但&lt;aws:Country&gt; 有。

【讨论】:

  • 谢谢@hek2mgl。您可以将root 更改为tree 以与我的代码保持一致。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-06
  • 1970-01-01
  • 2015-07-18
  • 1970-01-01
  • 1970-01-01
  • 2015-06-16
相关资源
最近更新 更多