Learn how to query XML datasets using XPath and XQuery. This tutorial is targeted to those with a background in SQL, but will still ...
XPath and XQuery are powerful tools for querying XML data, similar to how SQL is used for relational databases. This tutorial will help SQL users understand the basics of XPath and XQuery, drawing parallels to familiar SQL concepts.
Before diving into XPath and XQuery, let’s consider a sample XML document:
<library>
<book>
<title>Learning XQuery</title>
<author>John Doe</author>
<price>29.99</price>
</book>
<book>
<title>Mastering XPath</title>
<author>Jane Smith</author>
<price>19.99</price>
</book>
</library>
Selecting Nodes:
Select all books:
/library/book
Select titles of all books:
/library/book/title
Select books with a specific author:
/library/book[author='John Doe']
Using Wildcards:
/library/*
XQuery extends XPath by allowing data manipulation and transformation.
Basic Query:
To select all book titles:
for $book in doc("library.xml")/library/book
return $book/title
Filtering Results:
To return titles of books priced under $25:
for $book in doc("library.xml")/library/book
where $book/price < 25
return $book/title
Similar to SQL stored procedures, you can create functions in XQuery.
Example Function:
declare function local:filter-books($priceThreshold as xs:decimal) {
for $book in doc("library.xml")/library/book
where $book/price < $priceThreshold
return $book/title
};
Just as you would use COUNT()
or SUM()
in SQL, XQuery provides functions for aggregation:
Count Books:
count(doc("library.xml")/library/book)
XQuery can transform XML into other formats, like HTML.
HTML Output Example:
let $books := doc("library.xml")/library/book
return
<html>
<body>
{ for $book in $books return <p>{$book/title/text()}</p> }
</body>
</html>
XPath and XQuery provide powerful tools for querying and manipulating XML data, analogous to SQL for relational databases. Understanding their syntax and capabilities will enhance your ability to work with XML effectively. If you have specific questions or need further examples, feel free to ask!