Cover Image for XQuery Sequences
99 views

XQuery Sequences

In XQuery, a sequence is an ordered collection of zero or more items. These items can be XML elements, attributes, text nodes, numbers, strings, booleans, or even other sequences. Sequences allow you to work with multiple values together and perform operations on them as a single unit.

A sequence in XQuery is denoted by a comma-separated list of items wrapped in parentheses. For example:

(1, 2, 3, "hello", <person>John</person>, true())

In this example, the sequence contains six items: three integers, a string, an XML element <person>, and a boolean value true().

Sequences can also be empty, represented by an empty set of parentheses:

()

Sequence Functions and Operations:

XQuery provides various functions and operations to work with sequences. Some of the commonly used sequence functions and operations are:

  • fn:count(): Returns the number of items in a sequence.
  • fn:empty(): Checks if a sequence is empty.
  • fn:first(): Returns the first item in a sequence.
  • fn:last(): Returns the last item in a sequence.
  • fn:subsequence(): Extracts a subsequence from a sequence based on a starting position and length.
  • fn:distinct-values(): Returns a sequence containing only distinct values from the input sequence.
  • fn:insert-before(): Inserts items into a sequence before a specified position.
  • fn:remove(): Removes an item from a sequence at a specified position.
  • fn:concat(): Concatenates multiple sequences together.
  • fn:reverse(): Reverses the order of items in a sequence.
  • fn:filter(): Filters items in a sequence based on a specified condition.
  • fn:sort(): Sorts the items in a sequence in ascending order.
  • fn:sum(), fn:avg(), fn:max(), fn:min(): Aggregation functions for numeric sequences.

Sequences can also be constructed and manipulated using FLWOR expressions (For, Let, Where, Order by, Return), which allow you to iterate through sequences and perform operations on each item.

Examples of Sequence Operations:

let $numbers := (1, 2, 3, 4, 5)
let $doubled := $numbers ! ($item * 2)
return $doubled

In this example, we have a sequence of numbers stored in the variable $numbers. We use a FLWOR expression to iterate through each item in the sequence, double its value using the * operator, and store the results in the variable $doubled.

let $fruits := ("apple", "orange", "banana")
let $message := fn:string-join($fruits, ", ")
return $message

In this example, we have a sequence of strings representing fruits stored in the variable $fruits. We use the fn:string-join() function to concatenate these strings together with a comma separator and store the result in the variable $message.

Sequences are fundamental to XQuery, allowing you to process and manipulate collections of data efficiently.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS