XQuery Functions

The same functions library is shared by XQuery 1.0, XPath 2.0, and XSLT 2.0. Built on XPath expressions, XQuery 1.0 and XPath 2.0 share the same data model. They also support the same functions and operators. It also facilitates us to define our own functions in XQuery.

XQuery Data Types:

The same data types as XML Schema 1.0 (XSD) are shared by XQuery.

Examples of Function Calls:

An expression may appear for a call to a function to appear.


<?xml version="1.0" encoding="UTF-8"?>
  <book category="Child">
    <title lang="en">ABC</title>
    <author>Author Name</author>
  <book category="IT">
    <title lang="en">XQuery Book</title>
    <author>Author 1</author>
    <author>Author 2</author>
  <book category="Sociology">
    <title lang="en">Sociology 1</title>
    <author>Author Name</author>
  <book category="GK">
    <title lang="en">Current Affairs</title>
    <author>Author Name</author>
  <book category="Science">
    <title lang="en">Science Book</title>
    <author>Author 1</author>
    <author>Author 2</author>
    <author>Author 3</author>

Example 1: In an element:


Example 2: In the predicate of a path expression:


Example 3: In a let clause:

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

XQuery User-Defined Functions:

We can write our own XQuery function if we cannot find the one we need. In the query or a separate library is where we can define the user-defined functions.


declare function prefix:function_name($parameter as datatype)
as returnDatatype
 ...function code here...

User-defined functions:

  • The declare function keyword should be used.
  • Prefix the name of the function.
  • The data types defined in XML Schema is what the data type of the parameters should be mostly the same with.
  • The curly braces should be used to surround the body of the function.

Example: User-defined Function Declared in the Query:

declare function local:minCost($z as xs:decimal?,$y as xs:decimal?)
as xs:decimal?
let $disc := ($z * $y) div 100
return ($z - $disc)

Example: To call the above function:

Please Share