XQuery Functions

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

XQuery Functions

XQuery contains more than 100 built-in functions. These functions can be used for string values, numbers, date and time comparisons, node and QName operations, sequence operations, logical values, etc. 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 with the fn: prefix, such as fn:string(). However, since fn: is the default prefix for the namespace, the prefix does not need to be used when calling the function name.

You can find the complete 'Built-in XQuery Function Reference Manual》。

Function call examples

Function calls can be used with expressions. See the following examples:

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 the required XQuery function cannot be found, you can write your own function.

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

Syntax

declare function prefix:FunctionName($Parameter AS DataType)
  AS The data type of the returned data
{}}
(: ...function code... :)
;

Points to note about user-defined functions:

  • Please use the declare function keyword
  • The function name must use a prefix
  • The data type of the parameters is usually consistent with the data type defined in the XML Schema
  • The function body must be enclosed in curly braces

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

declare function local:minPrice(
  $price as xs:decimal?,
  $discount as xs:decimal?)
  AS xs:decimal?
{}}
let $disc := ($price * $discount) div 100
return ($price - $disc)
;
(Below is an example of calling the above function :)
<minPrice>{local:minPrice($book/price, $book/discount)}</minPrice>