lxml:元素上的 XPath 和命名空间



我在使用返回空列表的 XPath 查询时遇到问题。

更具体地说,XML 文档如下所示:

<rpc-reply xmlns:junos="http://xml.juniper.net/junos/15.1X22/junos">
<isis-database-information xmlns="http://xml.juniper.net/junos/15.1X22/junos-routing" junos:style="detail">
<isis-database>
<level>1</level>
<isis-database-entry>
<lsp-id>xxx.00-00</lsp-id>
<sequence-number>0xc2d6</sequence-number>
<checksum>0xe1d1</checksum>
</isis-database-entry>
</isis-database>
<isis-database>
<level>2</level>
<isis-database-entry>
<lsp-id>yyy.00-00</lsp-id>
<sequence-number>0x419e</sequence-number>
<checksum>0x1f24</checksum>
</isis-database-entry>
</isis-database>
</isis-database-information>
<cli>
<banner>{master}</banner>
</cli>
</rpc-reply>

这是我做的查询,也是基于堆栈溢出中的相关问题,

In [71]: docs = etree.fromstring(xxx)                                                                                                                 
In [72]: docs                                                                                                                                         
Out[72]: <Element rpc-reply at 0x7fc2e4c5eac8>
In [73]: docs.xpath("//isis-database-information/isis-database[level='2']/isis-database-entry")                                                       
Out[73]: []
In [74]: docs[0]                                                                                                                                      
Out[74]: <Element {http://xml.juniper.net/junos/15.1X22/junos-routing}isis-database-information at 0x7fc2e5876288>
In [76]: docs.xpath("//j:isis-database-information/j:isis-database[level='2']/j:isis-database-entry", namespaces={"j": "http://xml.juniper.net/junos/1
...: 5.1X22/junos-routing"})                                                                                                                      
Out[76]: []

我不明白命名空间和路径是如何一起玩的。 你能建议并告诉我我做错了什么吗?

看起来您只是缺少level上的j前缀...

//j:isis-database-information/j:isis-database[j:level='2']/j:isis-database-entry

最新更新