Welcome to this comprehensive guide on XQuery Sequence Functions! By the end of this lesson, you'll have a solid understanding of these powerful tools that help manipulate and extract data from XML documents.
Let's start from the basics.
XQuery Sequence Functions are a collection of built-in functions in XQuery that operate on sequences, such as nodes, items, and atomic values. They are used to perform various operations like filtering, sorting, and calculating values.
Before diving into the functions, let's clarify what a sequence is in XQuery. A sequence is an ordered collection of zero or more items, where each item can be a node, atomic value, or another sequence.
Now, let's explore some commonly used XQuery Sequence Functions.
The count() function returns the number of items in a sequence.
<xq:sequence select="count(//book)"/>In this example, //book returns all the book elements in the XML document, and count() counts the number of those elements.
The sum() function adds up all the numeric values in a sequence.
<xq:sequence select="sum(//book/price)"/>Here, //book/price selects all the price elements under book, and sum() calculates their total sum.
These functions find the minimum, maximum, and average values in a sequence, respectively.
<xq:sequence select="min(//book/price)"/>
<xq:sequence select="max(//book/price)"/>
<xq:sequence select="avg(//book/price)"/>These examples select the minimum, maximum, and average price of books in the XML document.
The distinct-values() function returns a sequence containing only unique values from the input sequence.
<xq:sequence select="distinct-values(//book/category)"/>This example returns a sequence with unique book categories from the XML document.
The reverse() function reverses the order of the items in a sequence.
<xq:sequence select="reverse(//book)"/>This example returns the books in the XML document in reverse order.
Let's put these functions into practice with a simple XML document containing book information:
<books>
<book id="1">
<title>Book 1</title>
<price>10.99</price>
<category>Fiction</category>
</book>
<book id="2">
<title>Book 2</title>
<price>15.99</price>
<category>Non-fiction</category>
</book>
<book id="3">
<title>Book 3</title>
<price>8.99</price>
<category>Fiction</category>
</book>
</books>Using the functions we've learned, we can query this document to extract various pieces of information.
What does the `count()` function do in XQuery?
Stay tuned for more in-depth lessons on XQuery and its various features! 🚀