XQuery - XPath

XQuery est compatible XPath. Il utilise des expressions XPath pour restreindre les résultats de la recherche sur les collections XML. Pour plus de détails sur l'utilisation de XPath, consultez notre didacticiel XPath .

Rappelez-vous l'expression XPath suivante que nous avons utilisée précédemment pour obtenir la liste des livres.

doc("books.xml")/books/book

Exemples XPath

Nous utiliserons le fichier books.xml et y appliquerons XQuery.

books.xml

<?xml version="1.0" encoding="UTF-8"?>
<books>
   
   <book category="JAVA">
      <title lang="en">Learn Java in 24 Hours</title>
      <author>Robert</author>
      <year>2005</year>
      <price>30.00</price>
   </book>
   
   <book category="DOTNET">
      <title lang="en">Learn .Net in 24 hours</title>
      <author>Peter</author>
      <year>2011</year>
      <price>40.50</price>
   </book>
   
   <book category="XML">
      <title lang="en">Learn XQuery in 24 hours</title>
      <author>Robert</author>
      <author>Peter</author> 
      <year>2013</year>
      <price>50.00</price>
   </book>
   
   <book category="XML">
      <title lang="en">Learn XPath in 24 hours</title>
      <author>Jay Ban</author>
      <year>2010</year>
      <price>16.50</price>
   </book>
   
</books>

Nous avons donné ici trois versions d'une instruction XQuery qui remplissent le même objectif d'afficher les titres de livres ayant une valeur de prix supérieure à 30.

XQuery - Version 1

(: read the entire xml document :)
let $books := doc("books.xml")

for $x in $books/books/book
where $x/price > 30
return $x/title

Production

<title lang="en">Learn .Net in 24 hours</title>
<title lang="en">Learn XQuery in 24 hours</title>

XQuery - Version 2

(: read all books :)
let $books := doc("books.xml")/books/book

for $x in $books
where $x/price > 30
return $x/title

Production

<title lang="en">Learn .Net in 24 hours</title>
<title lang="en">Learn XQuery in 24 hours</title>

XQuery - Version 3

(: read books with price > 30 :)
let $books := doc("books.xml")/books/book[price > 30]

for $x in $books
return $x/title

Production

<title lang="en">Learn .Net in 24 hours</title>
<title lang="en">Learn XQuery in 24 hours</title>

Vérifiez le résultat

Pour vérifier le résultat, remplacez le contenu de books.xqy (indiqué dans le chapitre Configuration de l' environnement ) par l'expression XQuery ci-dessus et exécutez le programme java XQueryTester.