2011-04-04 91 views
17

可能重複:
PHP SimpleXML. How to get the last item?
XSLT Select all nodes containing a specific substringPHP的XPath選擇最後一個匹配的元素

我需要找到的最後一個跨度元素的內容與類 'MyClass的' 的。我嘗試了各種組合,但找不到答案。

//span[@class='myPrice' and position()=last()] 

這將返回所有類「MyClass的」的元素,我猜這是因爲每一個找到的元素是最後的處理時間 - 但我只需要實際的最後一個匹配的元素。

+0

輸入xml請 – Gordon 2011-04-04 10:25:15

+0

@fabrik:我想不是。這將是更正確的:http://stackoverflow.com/questions/4672997/xslt-select-all-nodes-containing-a-specific-substring。這不是最後一個,但沒有'php'標籤... – 2011-04-04 12:57:51

回答

40

您必須爲處理器標記想要將//span[@class='myPrice']作爲當前集合,然後將謂詞position()= last()應用於該集合。

(//span[@class='myPrice'])[last()] 

例如,

<?php 
$doc = getDoc(); 
$xpath = new DOMXPath($doc); 
foreach($xpath->query("(//span[@class='myPrice'])[last()]") as $n) { 
    echo $n->nodeValue, "\n"; 
} 


function getDoc() { 
    $doc = new DOMDOcument; 
    $doc->loadxml(<<< eox 
<foo> 
    <span class="myPrice">1</span> 
    <span class="yourPrice">0</span> 
    <bar> 
    <span class="myPrice">4</span> 
    <span class="yourPrice">99</span> 
    </bar> 
    <bar> 
    <span class="myPrice">9</span> 
    </bar> 
</foo> 
eox 
); 
    return $doc; 
} 
+0

如何排除最後一行?實際上我想排除結果集中的最後兩行。這是可能的一個'xpath'表達式? – 2012-08-04 07:28:37

7

您使用的手段「,選擇每個span元素條件是:(a)其擁有@class='myprice',和(b)是其父的最後一個子有兩種錯誤的表達:

(1 ),則需要通過過濾@class,而不是將其應用到所有跨度元件後應用濾波器[position()=last()]

(2)的形式//span[last()]的表達式意味着/descendant-or-self::*/(child::span[last()]),其選擇的每個元素的最後一個子跨度。你需要使用圓括號改變優先順序:(//span)[last()]

因此,由VolkerK給出的表達式變成(//span[@class='myPrice'])[last()]

相關問題