Why is this Xquery expression returning a null value?

Viewed 267

I want to get the maximum value for an attribute. I have the following statement:

let $posts := doc("Posts.xml")/posts/row[./@OwnerUserId = $user/@Id]

let $maxScore := fn:max(xs:integer($posts/row/@Score))

When I want to return maxScore, it shows up as an empty value. Upon further tinkering, the following:

Return $posts/row/@Score

Also shows up as empty, even though I know each row has a 'Score' attribute

I've been fighting with this for over an hour, any help is appreciated

1 Answers

You are selecting the row elements that meet the criteria of your predicate. So, the $posts variable will have a sequence of row elements.

If you want to select the @Score from each of the row elements in the $posts variable, your XPath should be: $posts/@Score

It would be less confusing if you named the variable $rows.

Or, change the XPath to actually select posts elements:

let $posts := doc("Posts.xml")/posts[row/@OwnerUserId = $user/@Id]
let $maxScore := fn:max(xs:integer($posts/row/@Score))
Related