frgtv10
frgtv10

Reputation: 5450

Xquery get second product sorted by name

From the following XML I want to get the nth product sorted by their @name:

<products>
<product name='200'>...</product>
<product name='100'>...</product>
<product name='111'>...</product>
<product name='100'>...</product>
<product name='110'>...</product>
</products>

I tried (to get the first, but must be also working to get the third and so on...):

for $d in //products/product/[1]
order by $d/@name
return $d

I'm not getting the correct order. Only if I remove the [1] it works, but then I get the hole product list.

How to do a limit here?

Upvotes: 2

Views: 72

Answers (2)

Jens Erat
Jens Erat

Reputation: 38682

You're limiting at the wrong position (apart from the / before the predicate [1] being a syntax error).

Right now, you limit within the for loop's input specification, thus you're sorting over a single, namely the first product - which is obviously not what you're trying to achieve (and neither seems a reasonable thing to do).

To limit after performing the loop (and sorting), use a predicate wrapped around the loop:

(
  for $product in $xml//products/product
  order by $product/@name
  return $product
)[1]

Upvotes: 2

Ian Roberts
Ian Roberts

Reputation: 122364

Put the numeric predicate on the expression as a whole:

(
  for $d in //products/product
  order by $d/@name
  return $d
)[1]

The for generates the whole sequence of product elements ordered by name, the [1] is then an index into the sorted sequence.

Upvotes: 2

Related Questions