Подтвердить что ты не робот

Как использовать пустые пространства имен в запросе lxml xpath?

У меня есть 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="#" onclick="location.href='https://ip.ad.dr.ess:8000/feeds/diagnostics'; return false;"/>
    <link rel="edit" type="application/atom+xml" href="#" onclick="location.href='https://ip.ad.dr.ess:8000/feeds/diagnostics'; return false;"/>
    <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>

Мне нужно получить все элементы entry, используя xpath в lxml. Моя проблема в том, что я не могу понять, как использовать пустое пространство имен. Я пробовал следующие примеры, но никто не работает. Просьба сообщить.

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\"'):

В этот момент я просто не знаю, что попробовать. Любая помощь приветствуется.

4b9b3361

Ответ 1

Что-то вроде этого должно работать:

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

Ответ 2

Используйте findall метод.

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