PB138: XQuery

Hey, welcome to lab 4!

This time we will talk about XQuery

XQuery

  • XQuery is the language for querying XML data
  • Is it build on top of XPath and works like SQL for databases.
  • It is even suported by databases as querying language - see Posgres and XMLTable
 
for $x in doc("books.xml")/bookstore/book
where $x/price>30
order by $x/title
return $x/title

Looks like this

<ul>
{
for $x in doc("books.xml")/bookstore/book/title
order by $x
return <li>{$x}</li>
}
</ul>

You can even query to HTML

let $sum := sum(doc("books.xml")/bookstore/book/price)
return <ul>
{
for $x in doc("books.xml")/bookstore/book/title
order by $x
return <li>{$x}</li>
}
<li>Order x, total sum {$sum}</li>
</ul>

Or add variables

let $items := (1,2,3,4,5,"Different type", <div>Even HTML element</div>)
let $count := count($items)
return
   <result>
      <count>{$count}</count>
      
      <items>
      {
         for $item in $items[2]
         return <item>{$item}</item>
      }
      </items>
      
   </result>

Sequences

declare function local:write-paragraph($article) {
  for $text in $article/text return <p>{$text/node()}</p>
};

$article = doc("article.xml")/articles/article
local:write-paragraph($article)

Templates

Let's try it :) 

Btw nice tutorial is here: https://www.tutorialspoint.com/xquery/index.htm

PB138: XQuery

By Lukáš Grolig

PB138: XQuery

  • 405