Top Xquery Function

How can I achieve something similar to a TOP function, is it SQL using Xquery? In other words, how can I select the top 5 elements of something with bundles? It should be simple, but it's hard for me to find it on Google.

An example of some data that I would like to format looks like this:

<?xml version="1.0"?>
<root>
    <value> 
        <a>first</a>
        <b>1</b>
    </value>
    <value> 
        <a>third</a>
        <b>3</b>
    </value>
    <value> 
        <a>second</a>
        <b>2</b>
    </value>
    <value> 
        <a>2nd</a>
        <b>2</b>
    </value>
</root>

I want to sort by b for all values ​​and return a. To illustrate my problem, let's say I want to return the top two values ​​by relationships.

thank

+3
source share
5 answers

For the provided source XML document :

<root>
  <value> 
    <a>first</a>
    <b>1</b>
  </value>
  <value> 
    <a>third</a>
    <b>3</b>
  </value>
  <value> 
    <a>second</a>
    <b>2</b>
  </value>
  <value> 
    <a>2nd</a>
    <b>2</b>
  </value>
</root>

To get the first two results “with connections”, use :

let $vals := 
  for $k in distinct-values(/*/*/b/xs:integer(.)) 
    order by $k
    return $k
 return
  for $a in /*/value[index-of($vals,xs:integer(b)) le 2]/a
      order by $a/../b/xs:integer(.)
    return $a  

, , :

<a>first</a>
<a>second</a>
<a>2nd</a>

  • $vals /*/*/b, . , distinct-values() . , xs:integer , , , , .

  • /*/value/a, b- b-values 2.

  • , b-sibling integer,

:

/*/*/b.

+3

5 , fn:position():

$sequence[position() le 5]

, node /, . , , .

" " (, ) FLWOR.

XQuery:

(for $value in /root/value
 order by $value/b
 return $value/a)[position() le 2]

:

<a>first</a><a>second</a>

. . , .

XQuery:

for $key in (for $val in distinct-values(/root/value/b)
             order by xs:integer($val)
             return $val)[position() le 2]
return /root/value[b=$key]/a

:

<a>first</a><a>second</a><a>2nd</a>

: , .

: .

+2

XPath Node

    <one>
  <two>a</two>
  <two>b</two>
  <two>c</two>
  <two>d</two>
  <two>e</two>
  <two>f</two>
  <two>g</two>
  <two>h</two>
   </one>

$xml_data/one/two[ 1 to 5 ]

$xml_data/one/two[ some_number to fn:last() ]
+1

<one>
  <two>a</two>
  <two>b</two>
  <two>c</two>
  <two>d</two>
  <two>e</two>
  <two>f</two>
  <two>g</two>
  <two>h</two>
</one>

:

for $two at $index in /one/two
  where $index <= 5
  return $two
0

Source: https://habr.com/ru/post/1774740/