XQuery Examples

Estimated study time: 12 minutes.

Here are a few complete, practical XQuery examples using a simple course catalog to show common real-world patterns.

Sample Data

<!-- courses.xml -->
<courses>
  <course level="beginner">
    <title>Data Analytics</title>
    <seats>40</seats>
  </course>
  <course level="advanced">
    <title>Data Science</title>
    <seats>25</seats>
  </course>
</courses>

Example 1: Filter and List Titles

for $c in doc("courses.xml")//course
where $c/@level = "beginner"
return $c/title/text()

Example 2: Sort by Seats

for $c in doc("courses.xml")//course
order by $c/seats descending
return $c/title/text()

Example 3: Total Seats Across All Courses

sum(doc("courses.xml")//course/seats)

Example 4: Build a New HTML List

<ul>
{
  for $c in doc("courses.xml")//course
  return <li>{$c/title/text()}</li>
}
</ul>

This produces a complete HTML unordered list, generated dynamically from the underlying XML data.

💡 Tip: Test each XQuery expression against a small sample file first — it's much easier to debug an unexpected result on 3 records than on 3,000.

Ready to go beyond the basics?

Get hands-on training, live mentorship, and placement support with the Data Analytics Course at Uncodemy.

Explore XML Course →