Συνάρτησεις του XQuery

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

Συνάρτησεις του XQuery

XQuery contains more than 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

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 let statements

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:funcName($parameter AS dataType)
  AS The data type of the returned data
{}}
(: ...function code... :)
;

Considerations for user-defined functions:

  • Please use the declare function keyword
  • The function name must use a prefix
  • The data type of the parameters usually matches 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)
;
(: Εδώ είναι ένα παράδειγμα κλήσης της παραπάνω συνάρτησης :)
<minPrice>{local:minPrice($book/price, $book/discount)}</minPrice>