python - 如何在 lxml xpath 查询中使用默认命名空间?

标签 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>

我需要在 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

关于python - 如何在 lxml xpath 查询中使用默认命名空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8053568/

相关文章:

java - 每次页面加载后Xpath都会改变

python - 在 scipy.insterpolate 的 splrep 函数上选择节点的错误(?)

python - tensorflow : How to use restored model?

java - android:translationY 属性隐藏 Edittext 的下边框

ios - iOS 是否有一个好的基于 XML 的布局引擎?

java - 如何通过xpath获取重复标签的值,就像键值对

oop - python : What all implicit __xyz__ methods exists inside a default python class?

python - 就地递归反转列表

xml - 将 XML 文件转换为 lua 表?

html - XPath 选择包含文本的链接?