Ejemplos de XQuery

En esta sección, estudiaremos algunos fundamentos de la sintaxis de XQuery a través de un ejemplo.

Documento de ejemplo XML

Vamos a usar este documento XML en los ejemplos a continuación.

"books.xml" :

<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book category="COOKING">
  <title lang="en">Everyday Italian</title>
  <author>Giada De Laurentiis</author>
  <year>2005</year>
  <price>30.00</price>
</book>
<book category="CHILDREN">
  <title lang="en">Harry Potter</title>
  <author>J K. Rowling</author>
  <year>2005</year>
  <price>29.99</price>
</book>
<book category="WEB">
  <title lang="en">XQuery Kick Start</title>
  <author>James McGovern</author>
  <author>Per Bothner</author>
  <author>Kurt Cagle</author>
  <author>James Linn</author>
  <author>Vaidyanathan Nagarajan</author>
  <year>2003</year>
  <price>49.99</price>
</book>
<book category="WEB">
  <title lang="en">Learning XML</title>
  <author>Erik T. Ray</author>
  <year>2003</year>
  <price>39.95</price>
</book>
</bookstore>

Vea el archivo "books.xml" en su navegador..

¿Cómo seleccionar nodos desde "books.xml"?

Funciones

XQuery utiliza funciones para extraer datos de un documento XML.

doc() se utiliza para abrir el archivo "books.xml":

doc("books.xml")

Expresiones de ruta

XQuery utiliza expresiones de ruta para navegar por elementos en un documento XML.

Las expresiones de ruta a continuación se utilizan para seleccionar todos los elementos title en el archivo "books.xml":

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

(/bookstore selecciona el elemento bookstore, /book selecciona todos los elementos book bajo el elemento bookstore, y /title selecciona todos los elementos title bajo cada elemento book)

El XQuery superior puede extraer los siguientes datos:

<title lang="en">Everyday Italian</title>
<title lang="en">Harry Potter</title>
<title lang="en">XQuery Kick Start</title>
<title lang="en">Learning XML</title>

Predicado

XQuery utiliza predicados para limitar los datos extraídos de un documento XML.

Los siguientes predicados se utilizan para seleccionar todos los elementos book dentro del elemento bookstore, y el valor del elemento price seleccionado debe ser menor de 30:

doc("books.xml")/bookstore/book[price<30]

El XQuery superior puede extraer los siguientes datos:

<book category="CHILDREN">
  <title lang="en">Harry Potter</title>
  <author>J K. Rowling</author>
  <year>2005</year>
  <price>29.99</price>
</book>