Timmy
Timmy

Reputation: 745

How to extract the first element of a list in XQuery 1.0?

I want to extract the first element form the list $res/Name. In my solution I obtain all the list and not only the first element, here is what I wrote.

for $res in /Restaurants/Restaurant
let $n := count($res/Dish)
order by $n descending
return ($res/Name)[1]

You can see here the XML and the result: http://www.xpathtester.com/xquery/7992b12910492f493273835e828dc386

Where is the problem?

Upvotes: 3

Views: 9515

Answers (2)

Jens Erat
Jens Erat

Reputation: 38712

If you're able to use XQuery 3.0, it knows the helper functions fn:head($sequence) and fn:tail($sequence).

Example:

head(1 to 10)
1
tail(1 to 10)
2 3 4 5 6 7 8 9 10

Upvotes: 1

Gunther
Gunther

Reputation: 5256

The positional filter is part of the return clause expression, so you get the first Name for each $res.

However you want it to apply to the complete result. Moving the parentheses should solve that:

(
  for $res in /Restaurants/Restaurant
  let $n := count($res/Dish)
  order by $n descending
  return $res/Name
)[1]

Upvotes: 5

Related Questions