【问题标题】:lxml xpath.// and // difference [duplicate]lxml xpath.//和//区别[重复]
【发布时间】:2017-12-03 21:41:35
【问题描述】:
 <multi-routing-engine-item>

        <re-name>n</re-name>

        <zones-information xmlns="http://xml48/juzones" j:s="de">
            <zones-security>
                <zones-security-zonename>A</zones-security-zonename>
                <zones-security-interfaces>
                    <zones-security-interface-name>reth2.66</zones-security-interface-name>
                    <zones-security-interface-name>2.68</zones-security-interface-name>
                </zones-security-interfaces>
            </zones-security>
            <zones-security>        
                <zones-security-zonename>B</zones-security-zonename>

问题1:

 >>> response_zone.xpath("//zones-information/zones-security[//zones-security-interface-name[text()='reth2.66']]/zones-security-zonename/text()")
    ['A', 'B', 'C']
    >>> 
    >>> response_zone.xpath("//zones-information/zones-security[.//zones-security-interface-name[text()='reth2.66']]/zones-security-zonename/text()")
    ['A']

.// 和 // 在这种情况下有什么区别。有点迷茫。

问题2:

>>> response_zone.xpath(".//zones-security[.//zones-security-interface-name[text()='reth2.66']]/zones-security-zonename/text()")
['A']
>>> response_zone.xpath("//zones-security[.//zones-security-interface-name[text()='reth2.66']]/zones-security-zonename/text()") 
['A']

在 question2 中,他们有相同的结果.....

我对此感到困惑。需要帮助。

【问题讨论】:

  • . 指的是当前节点。如果查询以/// 开头,则它是相对于文档的根目录的。 // 遍历所有后代。把这些放在一起,你会得到什么?

标签: python xml xpath lxml


【解决方案1】:

阅读本文以了解 xPath https://en.wikipedia.org/wiki/XPath =)

. - self::node() 的缩写,当前节点的引用

// - 是/descendant-or-self::node()/的缩写,在所有层的所有节点内搜索

.// - 从当前节点搜索所有层

./从当前节点下一层搜索

所以当你这样做时:

//something[.//another] - something 在任何层上都有another

//something[./another] - somethinganother 为孩子

//something[//another] - something ,但在文件中的某处another 也应该是[不仅仅是在something 中,而是在任何地方]

//something//another - another 在任何层上都有 something 作为父级

//something/another - something 直接父母another

//something.//another - 错误,因为语法不正确,请使用 // 代替 =)

当您刚刚使用 //.// 启动定位器时 - 没有区别,因为起点是根文档元素,所以无论如何它都会在整个文件中搜索

【讨论】:

  • //something[//another] :如果它可以在某个地方找到另一个,xpath 会响应 //something 下的所有值。就像我得到的一样:response_zone.xpath("//zones-信息/zones-security[//zones-security-interface-name[text()='reth2.66']]/zones-security-zonename/text()") ['A', 'B', 'C '] . 我说的对吗?
  • 如果我使用 //something[//another],我想了解为什么它会响应所有 zone-secur‌​ity-zonename/text()
  • 因为您不是从当前节点搜索,所以使用 .// 代替=) 这就是 xpath 的工作原理,我不确定他们为什么以这种方式实现它。但是使用它,例如,您可以获取一些与当前节点完全无关的值(例如某些页面数量)并在当前节点中使用它。我认为这是主要原因。
  • 是的,我知道我不是从当前节点搜索 [//zones-security-interface-name[text()='reth2.66'] ,但整个路径是 :response_zone.xpath( "//zones-信息/zones-security[//zones-security-interface-name[text()='reth2.66']]/zones-security-zonename/text()") 。这个怎么理解?
猜你喜欢
  • 2021-04-26
  • 2018-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-08
相关资源
最近更新 更多