Working with Sequences in XQuery: Processing Ordered Data

Learn how to effectively create, manipulate, and process sequences in XQuery. This tutorial covers sequence creation, iteration using `for` loops, and common functions for working with sequences, providing essential techniques for efficient XML data querying and transformation.



Working with Sequences in XQuery

Understanding XQuery Sequences

In XQuery, a sequence is an ordered list of items. These items can be of different data types (numbers, strings, booleans, other XML nodes). Sequences are fundamental to XQuery because they are used to represent and process data retrieved from XML documents. Understanding how to create and work with sequences is essential for writing effective XQuery expressions.

Creating Sequences in XQuery

Sequences are created using parentheses `()` and separating items with commas. Items can be string literals (enclosed in single or double quotes), numbers, booleans, or XML nodes.

Example Sequence Creation

let $mySequence := ("apple", "banana", 1, 2, true)

Iterating Through Sequences

You can iterate over a sequence using a `for` loop. The example below shows a `for` loop used to iterate over the sequence and display each item.

Example XQuery (Iterating with `for` loop)

let $items := ('orange', 'banana', 'apple', 'sentro', 1, 2, 3, 'a', 'b', "abc")
let $count := count($items)
return
  $count,
  for $item in $items
  return $item

This code first creates a sequence named `$items`. It then uses `count()` to get the number of items and `for` to iterate and return each item.

Example: Using Index-Based Iteration

This example demonstrates an alternative approach that uses index-based iteration instead of directly looping through the sequence. It involves creating a sequence and then using a for loop to iterate over the sequence, using indexes to access items. This approach is less commonly used in XQuery. The output will display the number of items in the sequence followed by each item on a separate line.

Example XQuery (Index-Based Iteration)

let $items := (1, 2, 3, 4, 5, 6)
let $count := count($items)
return
  $count,
  for $i in 1 to $count
  return $items[$i]

Executing the XQuery (using Java and Saxon)

To run the XQuery code, you'll need an XQuery processor (like Saxon) and a Java program to execute the query. The Java code in the original instructions sets up a connection to the Saxon processor, executes the XQuery, and prints the result to the console.

Conclusion

Sequences are a fundamental concept in XQuery. They provide an ordered way to represent and work with data, enabling powerful data manipulation and transformation capabilities.