Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use XPath to find the minimum value of an attribute in a set of elements?

If I have XML like:

<foo>   <bar id="1" score="192" />   <bar id="2" score="227" />   <bar id="3" score="105" />   ... </foo> 

Can I use XPath to find the minimum and maximum values of score?

Edit: The tool i'm using (Andariel ant tasks) doesn't support the XPath 2.0 solution.

like image 473
brasskazoo Avatar asked Jul 15 '09 00:07

brasskazoo


People also ask

What is XPath by attribute?

Definition of XPath attribute. For finding an XPath node in an XML document, use the XPath Attribute expression location path. We can use XPath to generate attribute expressions to locate nodes in an XML document.

What is the meaning of '/' in XPath?

Single Slash “/” – Single slash is used to create Xpath with absolute path i.e. the xpath would be created to start selection from the document node/start node.


1 Answers

Here's a slightly shorter solution.

Maximum:

/foo/bar/@score[not(. < ../../bar/@score)][1] 

Minimum:

/foo/bar/@score[not(. > ../../bar/@score)][1] 

I've edited the predicate so that it's applicable to any sequence of bar, even if you decide to change the path. Note that parent of attribute is the element to which it belongs.

If embedding these queries in XML files like XSLT or ant scripts, remember to encode < and > as &lt; respecting &gt;.

like image 138
Pavel Minaev Avatar answered Sep 16 '22 14:09

Pavel Minaev