XQuery Introduction
Query and extract data from XML documents
🔍 What is XQuery?
XQuery is a powerful query language designed to retrieve and manipulate data from XML documents. Think of it as SQL for XML - it helps you find, filter, and extract specific information.
(: Simple XQuery example :)
for $book in doc("books.xml")//book
return $book/title
Why Use XQuery?
XQuery simplifies working with XML data by providing intuitive syntax for searching and extracting information. It's perfect for querying XML databases, transforming documents, and combining data from multiple sources efficiently.
Query XML
Search and filter XML data
Extract Data
Get specific information
Transform
Reshape XML structure
Combine
Join multiple XML sources
🔹 Basic XQuery Syntax
XQuery uses simple expressions to query XML:
📄 Sample XML (books.xml):
<library>
<book>
<title>XML Basics</title>
<author>John Doe</author>
<price>29.99</price>
</book>
<book>
<title>XQuery Guide</title>
<author>Jane Smith</author>
<price>39.99</price>
</book>
</library>
📄 Simple XQuery:
(: Get all book titles :)
doc("books.xml")//book/title
Result:
<title>XML Basics</title> <title>XQuery Guide</title>
🔹 XQuery Expressions
Common XQuery expressions for querying XML:
🔸 Path Expressions:
(: Navigate XML structure :)
doc("books.xml")/library/book/title
🔸 Filtering with Predicates:
(: Get books under $35 :)
doc("books.xml")//book[price < 35]
🔸 Extracting Text:
(: Get title text only :)
doc("books.xml")//book/title/text()
Result:
XML Basics XQuery Guide
🔹 XQuery Functions
Built-in functions for data manipulation:
🔸 Count Function:
(: Count total books :)
count(doc("books.xml")//book)
Result:
2
🔸 Sum Function:
(: Total price of all books :)
sum(doc("books.xml")//book/price)
Result:
69.98
🔸 String Functions:
(: Convert title to uppercase :)
upper-case(doc("books.xml")//book[1]/title)
Result:
XML BASICS
🔹 Conditional Queries
Use conditions to filter results:
(: Get expensive books :)
for $book in doc("books.xml")//book
where $book/price > 30
return $book/title
Result:
<title>XQuery Guide</title>
🔹 Creating New XML
XQuery can construct new XML from existing data:
(: Create summary XML :)
<summary>
{
for $book in doc("books.xml")//book
return <item>{$book/title/text()}</item>
}
</summary>
Result:
<summary>
<item>XML Basics</item>
<item>XQuery Guide</item>
</summary>
🔹 XQuery vs XSLT
When to use XQuery:
- Querying: Extracting specific data from XML
- Filtering: Finding elements that match criteria
- Calculations: Performing math on XML data
- Databases: Working with XML databases
When to use XSLT:
- Transformation: Converting XML to HTML/other formats
- Styling: Adding presentation to XML
- Templates: Reusable transformation patterns
🔹 Common XQuery Functions
- doc() - Load XML document
- count() - Count elements
- sum() - Add numeric values
- avg() - Calculate average
- max() - Find maximum value
- min() - Find minimum value
- concat() - Join strings
- substring() - Extract part of string