XQuery Functions
- Previous Page XQuery Selection
- Next Page XQuery Summary
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.
Built-in Functions of XQuery
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 prefix fn:, for example fn:string(). However, since fn: is the default namespace prefix, the prefix is not required when calling the function name.
You can find the completeReference Manual of Built-in XQuery Functions}.
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 a 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 the query or in an independent library.
Syntax
declare function prefix:function_name($parameter AS data_type)
AS Return Data Type
{
(: ...function code... :)
;
Considerations for user-defined functions:
- Use the declare function keyword
- The function name must use a prefix
- The data types of the parameters are usually consistent with the data types defined in XML Schema
- The function body must be enclosed in curly braces
Example of a user-defined function declared in a 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)
;
(Example of calling the function above :)
<minPrice>{local:minPrice($book/price, $book/discount)}</minPrice>
- Previous Page XQuery Selection
- Next Page XQuery Summary