gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:21:26 24 4
gpt4 key购买 nike

我有一个以下格式的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com