Updating counter in XQuery

后端 未结 7 1950
孤街浪徒
孤街浪徒 2020-12-10 13:39

I want to create a counter in xquery. My initial attempt looked like the following:

let $count := 0
for $prod in $         


        
7条回答
  •  没有蜡笔的小新
    2020-12-10 14:11

    Immutable variables

    XQuery is a functional programming language, which involves amongst others immutable variables, so you cannot change the value of a variable. On the other hand, a powerful collection of functions is available to you, which solves lots of daily programming problems.

    let $count := 0
    for $prod in $collection]
      let $count := $count + 1
    return 
    {$count }
    

    let $count in line 1 defines this variable in all scope, which are all following lines in this case. let $count in line 3 defines a new $count which is 0+1, valid in all following lines within this code block - which isn't defined. So you indeed increment $count three times by one, but discard the result immediatly.

    BaseX' query info shows the optimized version of this query which is

    for $prod in $collection
      return element { "counter" } { 1 }
    

    The solution

    To get the total number of elements in $collection, you can just use

    return count($collection)
    

    For a list of XQuery functions, you could have a look at the XQuery part of functx which contains both a list of XQuery functions and also some other helpful functions which can be included as a module.

提交回复
热议问题