XQuery - XPath

XQuery es compatible con XPath. Utiliza expresiones XPath para restringir los resultados de búsqueda en colecciones XML. Para obtener más detalles sobre cómo utilizar XPath, consulte nuestro Tutorial de XPath .

Recuerde la siguiente expresión XPath que hemos utilizado anteriormente para obtener la lista de libros.

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

Ejemplos de XPath

Usaremos el archivo books.xml y le aplicaremos 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>

Hemos proporcionado aquí tres versiones de una declaración XQuery que cumplen el mismo objetivo de mostrar los títulos de los libros con un valor de precio superior a 30.

XQuery - Versión 1

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

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

Salida

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

XQuery - Versión 2

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

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

Salida

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

XQuery - Versión 3

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

for $x in $books
return $x/title

Salida

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

Verificar el resultado

Para verificar el resultado, reemplace el contenido de books.xqy (dado en el capítulo Configuración del entorno ) con la expresión XQuery anterior y ejecute el programa java XQueryTester.