[英]how do I use empty namespaces in an lxml xpath query?
我有以下格式的 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\"'):
在這一點上,我只是不知道該嘗試什么。 任何幫助是極大的贊賞。
這樣的事情應該工作:
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
使用findall方法。
for item in tree.findall('{http://www.w3.org/2005/Atom}entry'):
print item
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.