XQuery Functions
XQuery 1.0, XPath 2.0, and XSLT 2.0 share the same function library.
XQuery Functions
XQuery contains over 100 built-in functions. These functions can be used for string values, numeric values, date and time comparisons, node and QName operations, sequence operations, logical values, and more. You can also define your own functions in XQuery.
XQuery built-in functions
The 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, e.g., fn:string(). However, since fn: is the default prefix of the namespace, the function name does not need the prefix when called.
You can find the completeBuilt-in XQuery Function Reference Manual".
Function call examples
Function calls can be used together with expressions. Please look at the example below:
Example 1: in an element
Example 2: in the predicate of a path expression
doc("books.xml")/bookstore/book[substring(title,1,5)='Harry']
Example 3: in a let statement
let $name := (substring($booktitle,1,4))
XQuery user-defined functions
If you cannot find the required XQuery function, you can write your own function.
User-defined functions can be defined in the query or in a separate library.
Syntax
declare function
prefix:function name
($
Parameters
AS
Data Type
)
AS
return 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 parameters usually matches the data types defined in XML Schema
- The function body must be enclosed in curly 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: