XQuery Functions and Operators

XQuery is a powerful language used for querying and manipulating XML data. At the heart of XQuery are its functions and operators, which allow you to perform a wide range of operations on XML documents, from simple data retrieval to complex data transformations. Understanding how to use XQuery functions and operators is essential for any XML developer because it enables efficient querying, filtering, and manipulation of XML data.

What is XQuery?

XQuery is a query language designed specifically for querying XML documents. It allows you to extract and manipulate XML data easily. XQuery is a W3C recommendation and is widely used in XML databases, web services, and applications that require XML processing.

Key Features of XQuery

  • XPath Integration: XQuery builds upon XPath, enabling you to use powerful path expressions to navigate XML trees.
  • FLWOR Expressions: XQuery’s most prominent feature is the FLWOR expression, which allows you to iterate, filter, and organize XML data.
  • Modularity: XQuery allows you to define and reuse functions, improving the modularity of your code.

XQuery Functions

Functions in XQuery are used to perform specific tasks, such as string manipulation, mathematical operations, or working with sequences. XQuery provides a rich set of built-in functions that you can use right away, and you can also define your own user-defined functions for more specific needs.

Built-in Functions

XQuery comes with a wide variety of built-in functions that are organized into different categories. Let’s explore some of the most commonly used built-in functions with examples.

1. String Functions

String functions are used to manipulate and work with text in XML data.

  • fn:concat(): Concatenates two or more strings.
				
					let $title := "XQuery"
let $version := "3.1"
return fn:concat($title, " Version ", $version)

				
			

Output:

				
					XQuery Version 3.1

				
			
  • fn:substring(): Extracts a substring from a string.
 
				
					let $str := "XQuery is powerful"
return fn:substring($str, 1, 6)

				
			

Output: 

				
					XQuery

				
			

2. Mathematical Functions

Mathematical functions are used to perform arithmetic and other mathematical operations on numeric data.

  • fn:sum(): Returns the sum of a sequence of numbers.
				
					let $numbers := (10, 20, 30)
return fn:sum($numbers)

				
			

Output:

				
					60
				
			
  • fn:round(): Rounds a number to the nearest integer.
				
					let $num := 12.56
return fn:round($num)

				
			

Output:

				
					13

				
			

3. Date and Time Functions

XQuery provides functions to manipulate date and time values.

  • fn:current-dateTime(): Returns the current date and time.
				
					return fn:current-dateTime()

				
			

Output (example):

				
					2024-10-13T12:34:56Z

				
			
  • fn:year-from-date(): Extracts the year from a date.
				
					let $date := xs:date("2024-10-13")
return fn:year-from-date($date)
				
			

Output:

				
					2024
				
			

4. Node Functions

Node functions are essential for working with XML nodes, such as elements, attributes, and namespaces.

  • fn:count(): Returns the number of items in a sequence.
				
					let $books := <library>
                 <book>Book 1</book>
                 <book>Book 2</book>
             </library>
return fn:count($books/book)

				
			

Output:

				
					2

				
			
  • fn:name(): Returns the name of a node.
				
					let $book := <book>Learning XML</book>
return fn:name($book)

				
			

Output:

				
					book
				
			

User-Defined Functions

In addition to built-in functions, you can define your own functions in XQuery. User-defined functions allow you to create reusable blocks of code for complex operations.

Syntax of a User-Defined Function

				
					declare function local:function-name($param as data-type) as return-type {
    expression
};

				
			

Example: Defining and Using a Function

				
					declare function local:add($a as xs:integer, $b as xs:integer) as xs:integer {
    $a + $b
};

let $result := local:add(10, 20)
return $result
				
			

Output:

				
					30

				
			

Explanation:

  • declare function: Declares a function.
  • local:add: The function name.
  • $a, $b: Parameters of type xs:integer.
  • $a + $b: The expression that adds the two integers.

XQuery Operators

Operators in XQuery are used to perform operations on data. XQuery supports a variety of operators, including arithmetic, comparison, and logical operators.

Arithmetic Operators

  • +: Addition
  • -: Subtraction
  • *: Multiplication
  • div: Division

Example: Using Arithmetic Operators

				
					let $a := 15
let $b := 5
return ($a + $b, $a - $b, $a * $b, $a div $b)

				
			

Output:

				
					20 10 75 3
				
			

Comparison Operators

  • =: Equality
  • !=: Inequality
  • >: Greater than
  • <: Less than

Example: Using Comparison Operators

				
					let $x := 10
let $y := 20
return ($x = $y, $x != $y, $x > $y, $x < $y)

				
			

Output:

				
					false true false true

				
			

Logical Operators

  • and: Logical AND
  • or: Logical OR
  • not(): Logical NOT

Example: Using Logical Operators

				
					let $a := true()
let $b := false()
return ($a and $b, $a or $b, not($a))
				
			

Output:

				
					false true false
				
			

FLWOR Expressions

One of the most powerful features in XQuery is the FLWOR (For-Let-Where-Order by-Return) expression. FLWOR allows you to iterate over sequences, filter results, sort them, and return the output.

Basic Structure of FLWOR

				
					for $var in sequence
let $var2 := expression
where condition
order by expression
return result
				
			

Example: Using FLWOR

				
					let $books := <library>
                 <book><title>XQuery Basics</title></book>
                 <book><title>Advanced XQuery</title></book>
             </library>
for $book in $books/book
where fn:contains($book/title, "XQuery")
return $book/title
				
			

Output:

				
					<title>XQuery Basics</title>
<title>Advanced XQuery</title>

				
			

Explanation:

  • for $book in $books/book: Iterates over all the book elements.
  • where: Filters books with “XQuery” in the title.
  • return: Returns the titles of the filtered books.

Advanced XQuery Functions and Operators

Working with Sequences

A sequence in XQuery is an ordered collection of items (nodes or atomic values). XQuery provides functions to work with sequences, such as joining, intersecting, or returning distinct values.

Example: fn:distinct-values()

				
					let $numbers := (1, 2, 2, 3, 3, 3)
return fn:distinct-values($numbers)
				
			

Output:

				
					Output:
				
			

Conditional Expressions

XQuery supports conditional expressions using if-then-else, allowing you to include logic in your queries.

Example: Using if-then-else

				
					let $age := 20
return if ($age >= 18) then "Adult" else "Minor"
				
			

Output:

				
					Adult
				
			

We have explored XQuery functions and operators in depth, covering the most important built-in functions, user-defined functions, arithmetic, comparison, and logical operators. We have also discussed how to use FLWOR expressions and conditional logic in XQuery. By mastering these concepts, you can harness the full power of XQuery to query, filter, and manipulate XML data efficiently. Happy Coding!❤️

Table of Contents