2012-12-23 47 views
1

我已經涉及到這個問題的其他幾個問題:的XPath找出什麼孩子數是衆多兄弟姐妹

getting a parent node and its child, where the child has a certain text

XPath finding certain node with certain text

比方說這是我的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個跨度的孩子的div,從上到下數2。有沒有一種方法來計算programmaticaly?

+0

你只需要得到的孩子,你的父母匹配的孩子,並且循環在他們遞增,直到你匹配的孩子 – 2012-12-23 18:18:15

+0

我想到的數做一個'foreach'兒童並搜索文字,直到找到合適的孩子,但我不知道如何訪問兒童。像訪問屬性它會是$ node->屬性。我如何訪問其子女? –

回答

1

使用XPath,您可以通過$count = $xpath->evaluate("count(. | preceding-sibling::*)", $node-with-value->item(0))來找到兄弟元素的數字或$count = $xpath->evaluate("count(. | preceding-sibling::node())", $node-with-value->item(0)),以找到兄弟節點(即元素節點,但文本,註釋和處理指令節點)的數字。

+0

非常感謝你的作品,比我的更好 –

0

再純的XPath的解決方案

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