Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

XQuery function


May 28, 2021 XQuery


Table of contents


XQuery function

There are many built-in functions in XQuery, and this section describes how to call or customize XQuery functions.

XQuery 1.0, XPath 2.0, and XSLT 2.0 share the same library.


XQuery function

XQuery contains more than 100 built-in functions. T hese functions can be used for string values, numeric values, date and time comparisons, node and QName operations, sequence operations, logical values, and so on. You can also define your own functions in XQuery.


XQuery built-in functions

URI of the XQuery function namespace:

http://www.w3.org/2005/02/xpath-functions

The default prefix for the function namespace is fn:.

Tip: Functions are often called through the fn: prefix, such as fn:string(). However, because fn: is the default prefix for the namespace, the function name does not have to be used when called.

You can find the complete Built-in XQuery Function Reference Manual in our XPath tutorial.


The function calls the instance

Function calls can be used with expressions. Take a look at the following example:

Example 1: In an element

<name>{upper-case($booktitle)}</name>

Example 2: In the predicate of a path expression

doc("books.xml")/bookstore/book[substring(title,1,5)='Harry']

Example 3: In the let statement

let $name := (substring($booktitle,1,4))


XQuery user-defined functions

If you can't find the XQuery function you want, you can write your own.

User-defined functions can be defined in queries or in separate libraries.

Grammar

declare function Prefix: Function Name ($ parameter AS type of data )
AS Returned data type
{
... Function code ...
}

Notes on user-defined functions:

  • Please use the declare function keyword
  • The function name must use a prefix
  • The data type of the parameter is usually the same as the data type defined in XML Schema
  • The function body must be surrounded by braces

An example of a user-defined function declared in a query:

declare function local:minPrice($p as xs:decimal?,$d as xs:decimal?)
AS xs:decimal?
{
let $disc := ($p * $d) div 100
return ($p - $disc)
}

Below is an example of how to call the function above:

<minPrice>{local:minPrice($book/price,$book/discount)}</minPrice>