Xquery functions

Xquery functions:

Functions are a set of instructions bundled together to achieve a specific outcome. Functions are a good alternative to having repeating blocks of code in a program. Values can be passed to a function using variables – we call these parameters or arguments.

XQuery provides the capability to write custom functions. Listed below are the guidelines to create a custom function.

  • We can use predefined XQuery functions in code.
  • We can also declare custom functions as per our requirements.
  • Method overloading can be used in Xquery.
  • Method recursion can be used in Xquery also.
Below is the syntax to create custom functions in Xquery:

declare function prefix:function_name($parameter as datatype)
as returnDatatype
{
 ...function code here...
};


Recursive functions example:

1.
declare function local:check-num($num as xs:int)
{
 let $result :=   if($num gt 2)
then (
let $cal := ($num - 1)
return local:check-num($cal)
     )
else(
                 if($num eq 1)
                 then fn:concat("Now values of number is", $num)
                 else fn:concat("Now values of number is++++", $num)
               ) 
  
return $result   
};

local:check-num(10)

2.

declare function local:retrieve-file-name($path as xs:string)
{
  let $inside-directory := xdmp:filesystem-directory($path)/dir:entry
   for $each in $inside-directory
     return if($each/dir:type/text() eq "file")
     
     then fn:concat("inside file ==", $each/dir:filename/text())
        else local:retrieve-file-name($each/dir:pathname/text())

};

let $dir := xdmp:filesystem-directory("D:\XQuery\")/dir:entry

  for $each in $dir
    let $file-name := $each/dir:filename/text()
    let $folder-path := $each/dir:pathname/text()
    let $file-type := $each/dir:type/text()
    return
      if($file-type eq "file") then fn:concat("outside file ==", $file-name)
       else local:retrieve-file-name($folder-path)


Comments

Popular posts from this blog

HTTP Servers, Database, Forest

Xquery

Marklogic Fundamentals