Xpath查找其他兄弟姐妹中的子编号


xpath finding out what child number is amongst other siblings

我有几个与这个主题相关的其他问题:

获取父节点及其子节点,其中子节点具有特定的文本

和XPath查找具有特定文本的特定节点

假设这是我的HTML:

<body>
    <div>
          <span>something else</span>
          <span>something</span>
          <span>something else</span>
    <div>
</body>

我使用以下命令查询具有特定文本的节点:

$node_with_value = $xpath->query('(//*[text()= "'something"])');

返回具有某项的所有节点的列表。在本例中,它将仅为1。

找到它的父节点parent = $node_with_value->item(0)->parentNode;

现在我的问题是我如何检查它是多少个子。

在上面的

中,我们有3个span子div,从上到下计数它的数字2。有没有办法用程序来计算?

使用XPath,您可以执行$count = $xpath->evaluate("count(. | preceding-sibling::*)", $node-with-value->item(0))以查找兄弟元素的数量或$count = $xpath->evaluate("count(. | preceding-sibling::node())", $node-with-value->item(0))以查找兄弟节点的数量(即元素节点,但文本,注释和处理指令节点)。

又是一个纯XPath解决方案:

count(/*/*/span[.='something']/preceding-sibling::*) +1