stee1rat
stee1rat

Reputation: 730

Need some explanation about getting max in XPath

I'm kinda new to XPath and I've found that to get the max attribute number I can use the next statement: //Book[not(@id > //Book/@id) and it works quite well.

I just can't understand why does it return max id instead of min id, because it looks like I'm checking whether id of a node greater than any other nodes ids and then return a Book where it's not.

I'm probably stupid, but, please, someone, explain :)

Upvotes: 3

Views: 987

Answers (2)

Jens Erat
Jens Erat

Reputation: 38682

You're not querying for maximum values, but for minimum values. Your query

//Book[not(@id > //Book/@id)

could be translated to natural language as "Find all books, which do not have an @id that is larger than any other book's @id". You probably want to use

//Book[not(@id < //Book/@id)

For arbitrary input you might have wanted to use <= instead, so it only returns a single maximum value (or none if it is shared). As @ids must be unique, this does not matter here.

Be aware that //Book[@id > //Book/@id] is not equal to the query above, although math would suggest so. XPath's comparison operators adhere to a kind of set-semantics: if any value on the left side is larger than any value on the right side, the predicate would be true; thus it would include all books but the one with minimum @id value.

Upvotes: 2

Vignesh Kumar A
Vignesh Kumar A

Reputation: 28403

Besides XPath 1.0 your function is correct, in XPath 2.0:

/Books/Book[id = max(../Book/id)]

The math:max function returns the maximum value of the nodes passed as the argument. The maximum value is defined as follows. The node set passed as an argument is sorted in descending order as it would be by xsl:sort with a data type of number. The maximum is the result of converting the string value of the first node in this sorted list to a number using the number function.

If the node set is empty, or if the result of converting the string values of any of the nodes to a number is NaN, then NaN is returned.

The math:max template returns a result tree fragment whose string value is the result of turning the number returned by the function into a string.

Upvotes: 0

Related Questions