繁体   English   中英

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

[英]lxml: XPath and namespaces on an element

我在使用返回结果为空列表的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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM