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

ewo*_*wok 25 python xml xpath lxml

我有一个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>
Run Code Online (Sandbox Code Playgroud)

我需要entry在lxml中使用xpath 检索所有元素.我的问题是我无法弄清楚如何使用空名称空间.我尝试过以下示例,但都没有效果.请指教.

import lxml.etree as et

tree=et.fromstring(xml)    
Run Code Online (Sandbox Code Playgroud)

我尝试过的各种事情是:

for node in tree.xpath('//entry'):
Run Code Online (Sandbox Code Playgroud)

要么

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):
Run Code Online (Sandbox Code Playgroud)

要么

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

在这一点上,我只是不知道该尝试什么.任何帮助是极大的赞赏.

mzj*_*zjn 37

这样的事情应该有效:

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
Run Code Online (Sandbox Code Playgroud)

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

替代方案:

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

  • 所以这里没有办法使用默认命名空间?我问,因为它使得更容易使用文档中出现的实际标记,即`<entry>`,而不是`<atom:entry>` (4认同)
  • `local-name`技巧是一个很好的技巧,用于在命名空间中查找未命名空间的元素。 (2认同)