解析带有空namesp的xml

2024-04-25 04:29:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用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,因为没有列表。你知道吗


Tags: orgcomhttpwwwerrorxmlopensearchatom
1条回答
网友
1楼 · 发布于 2024-04-25 04:29:56

您需要使用您为表达式中的空命名空间提供的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

相关问题 更多 >