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:
ABC Author Name 2020 100.00 XQuery Book Author 1 Author 2 2005 300.00 Sociology 1 Author Name 2010 250.00 Current Affairs Author Name 2004 500.00 Science Book Author 1 Author 2 Author 3 2011 150.00
Example 1: In an element:
{upper-case($booktitle)}
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:
{local:minCost($book/price,$book/discount)}