gpt4 book ai didi

python - 使用空命名空间解析 xml

转载 作者:太空宇宙 更新时间:2023-11-03 16:56:58 25 4
gpt4 key购买 nike

我使用lxml解析格式正确的 xml:

<search-results xmlns="http://www.w3.org/2005/Atom"
xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:prism="http://prismstandard.org/namespaces/basic/2.0/"
xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/"
xmlns:dc="http://purl.org/dc/elements/1.1/">
<opensearch:totalResults>0</opensearch:totalResults>
<opensearch:startIndex>0</opensearch:startIndex>
<opensearch:itemsPerPage>0</opensearch:itemsPerPage>
<entry>
<error>Result set was empty</error>
</entry>
</search-results>

我对 error 里面的文字感兴趣.

我使用了以下代码:

from lxml import etree

doc = etree.fromstring(xml) # xml is above xml

ns = {'opensearch': "http://a9.com/-/spec/opensearch/1.1/"}
print doc.xpath('//opensearch:totalResults', namespaces=ns)[0].text

这可以很好地获得 0 ,但是我应该为 <entry> 做什么? ,它似乎不在命名空间中?我尝试添加空命名空间,我认为它与 "http://www.w3.org/2005/Atom" 相关。 :

ns = {'opensearch': "http://a9.com/-/spec/opensearch/1.1/", 'empty': "http://www.w3.org/2005/Atom"}
print doc.xpath('//entry/error', namespaces=ns)[0].text

但这会导致 IndexError ,因为没有列表。

最佳答案

您需要使用为表达式内的空命名空间提供的 empty 别名:

ns = {'opensearch': "http://a9.com/-/spec/opensearch/1.1/", 'empty': "http://www.w3.org/2005/Atom"}
print doc.xpath('//empty:entry/empty:error', namespaces=ns)[0].text

关于python - 使用空命名空间解析 xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35349970/

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