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.

Books.xml:

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
 
  <book category="Child">
    <title lang="en">ABC</title>
    <author>Author Name</author>
    <year>2020</year>
    <price>100.00</price>
  </book>
 
  <book category="IT">
    <title lang="en">XQuery Book</title>
    <author>Author 1</author>
    <author>Author 2</author>
 <year>2005</year>
    <price>300.00</price>
  </book>
 
  <book category="Sociology">
    <title lang="en">Sociology 1</title>
    <author>Author Name</author>
 <year>2010</year>
    <price>250.00</price>
  </book>
 
  <book category="GK">
    <title lang="en">Current Affairs</title>
    <author>Author Name</author>
 <year>2004</year>
    <price>500.00</price>
  </book>
 
  <book category="Science">
    <title lang="en">Science Book</title>
    <author>Author 1</author>
    <author>Author 2</author>
    <author>Author 3</author>
 <year>2011</year>
    <price>150.00</price>
  </book>
 
</bookstore>

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,6)='XQuery']

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.

Syntax:

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:

<minCost>{local:minCost($book/price,$book/discount)}</minCost>
Please Share