如何在lxml xpath查询中使用空名称空间?

2024-04-19 10:13:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个xml文档,格式如下:

<feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:gsa="http://schemas.google.com/gsa/2007">
  ...
  <entry>
    <id>https://ip.ad.dr.ess:8000/feeds/diagnostics/smb://ip.ad.dr.ess/path/to/file</id>
    <updated>2011-11-07T21:32:39.795Z</updated>
    <app:edited xmlns:app="http://purl.org/atom/app#">2011-11-07T21:32:39.795Z</app:edited>
    <link rel="self" type="application/atom+xml" href="https://ip.ad.dr.ess:8000/feeds/diagnostics"/>
    <link rel="edit" type="application/atom+xml" href="https://ip.ad.dr.ess:8000/feeds/diagnostics"/>
    <gsa:content name="entryID">smb://ip.ad.dr.ess/path/to/directory</gsa:content>
    <gsa:content name="numCrawledURLs">7</gsa:content>
    <gsa:content name="numExcludedURLs">0</gsa:content>
    <gsa:content name="type">DirectoryContentData</gsa:content>
    <gsa:content name="numRetrievalErrors">0</gsa:content>
  </entry>
  <entry>
    ...
  </entry>
  ...
</feed>

我需要在lxml中使用xpath检索所有entry元素。我的问题是我不知道如何使用空名称空间。我试过下面的例子,但没有成功。请告知。

import lxml.etree as et

tree=et.fromstring(xml)    

我尝试过的各种事情是:

for node in tree.xpath('//entry'):

或者

namespaces = {None:"http://www.w3.org/2005/Atom" ,"openSearch":"http://a9.com/-/spec/opensearchrss/1.0/" ,"gsa":"http://schemas.google.com/gsa/2007"}

for node in tree.xpath('//entry', namespaces=ns):

或者

for node in tree.xpath('//\"{http://www.w3.org/2005/Atom}entry\"'):

在这一点上,我只是不知道该尝试什么。任何帮助都非常感谢。


Tags: nameorgipcomapphttpxmlcontent
2条回答

使用findall方法。

for item in tree.findall('{http://www.w3.org/2005/Atom}entry'): 
    print item

这样的做法应该管用:

import lxml.etree as et

ns = {"atom": "http://www.w3.org/2005/Atom"}
tree = et.fromstring(xml)
for node in tree.xpath('//atom:entry', namespaces=ns):
    print node

另请参见http://lxml.de/xpathxslt.html#namespaces-and-prefixes

备选方案:

for node in tree.xpath("//*[local-name() = 'entry']"):
    print node

相关问题 更多 >