Getting the highest node value using XPath

In XPath, how can I get the node with the highest value? eg

<tr>
   <td>$12.00</td>
   <td>$24.00</td>
   <td>$13.00</td>
</tr> 

will return $ 24.00.

I am using the PHP DOM, so it will be XPath version 1.0.

+3
source share
3 answers

I spend the last little while trying to come up with the most elegant solution for you. As you know, maxit is not available in XPath 1.0. I tried several different approaches, most of which are not very effective.

<?php

$doc = new DOMDocument;
$doc->loadXml('<table><tr><td>$12.00</td><td>$24.00</td><td>$13.00</td></tr></table>');

function dom_xpath_max($this, $nodes)
{
  usort($nodes, create_function('$a, $b', 'return strcmp($b->textContent, $a->textContent);'));

  return $this[0]->textContent == $nodes[0]->textContent;
}

$xpath = new DOMXPath($doc);
$xpath->registerNamespace('php', 'http://php.net/xpath');
$xpath->registerPHPFunctions('dom_xpath_max');

$result = $xpath->evaluate('//table/tr/td[php:function("dom_xpath_max", ., ../td)]');

echo $result->item(0)->textContent;

?>

Alternatively, you can use a loop foreachto repeat the result of a simpler XPath expression (once that selects only all TD elements) and dials the largest number.

<?php

...

$xpath = new DOMXPath($doc);

$result = $xpath->evaluate('//table/tr/td');

$highest = '';

foreach ( $result as $node )
  if ( $node->textContent > $highest )
    $highest = $node->textContent;

echo $highest;

?>

XSLTProcessor XSL-, math: max exslt.org, - ($).

, .

+2

, XPath, , , , $. XML, $

<tr>
   <td>12.00</td>
   <td>24.00</td>
   <td>13.00</td>
</tr> 

XPath node. //tr/td[not(preceding-sibling::td/text() > text() or following-sibling::td/text() > text())]

<td> 24.00.

, .

+2

XPath 1.0 : XSLT , , XPath. PHP max() PHP-.

+1

All Articles