XPath / XQuery Tutorial for SQL Pros

Blessings Photo

Blessings
7 years 1 Views
Category:
Description:

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 Tutorial for SQL Users

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.

1. Introduction to XPath and XQuery

  • XPath: A language for navigating through elements and attributes in XML documents. It allows you to select nodes or sets of nodes.
  • XQuery: A functional programming language that builds on XPath, designed for querying and transforming XML data.

2. XML Structure

Before diving into XPath and XQuery, let’s consider a sample XML document:

xml
<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>

3. XPath Basics

Selecting Nodes:

  • Select all books:

    xpath
    /library/book
    
  • Select titles of all books:

    xpath
    /library/book/title
    
  • Select books with a specific author:

    xpath
    /library/book[author='John Doe']
    

Using Wildcards:

  • Select all elements:
    xpath
    /library/*
    

4. XQuery Basics

XQuery extends XPath by allowing data manipulation and transformation.

Basic Query:

To select all book titles:

xquery
for $book in doc("library.xml")/library/book
return $book/title

Filtering Results:

To return titles of books priced under $25:

xquery
for $book in doc("library.xml")/library/book
where $book/price < 25
return $book/title

5. Creating Functions in XQuery

Similar to SQL stored procedures, you can create functions in XQuery.

Example Function:

xquery
declare function local:filter-books($priceThreshold as xs:decimal) {
  for $book in doc("library.xml")/library/book
  where $book/price < $priceThreshold
  return $book/title
};

6. Aggregating Data

Just as you would use COUNT() or SUM() in SQL, XQuery provides functions for aggregation:

Count Books:

xquery
count(doc("library.xml")/library/book)

7. Transforming XML Data

XQuery can transform XML into other formats, like HTML.

HTML Output Example:

xquery
let $books := doc("library.xml")/library/book
return
  <html>
    <body>
      { for $book in $books return <p>{$book/title/text()}</p> }
    </body>
  </html>

8. Conclusion

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!