Ejemplo XQuery
- Página anterior Introducción a XQuery
- Página siguiente FLWOR XQuery
En esta sección, vamos a aprender algunas gramáticas básicas de XQuery a través de un ejemplo.
Documento de ejemplo XML
Vamos a usar este documento XML en los ejemplos siguientes.
"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>
¿Cómo seleccionar nodos de "books.xml"?
Función
XQuery utiliza funciones para extraer datos de un documento XML.
doc() se utiliza para abrir el archivo "books.xml":
doc("books.xml")
Expresión de路径
XQuery utiliza expresiones de路径 para navegar por los elementos en un documento XML.
La expresión de路径 siguiente se utiliza 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 anterior 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 predicados siguientes se utilizan para seleccionar todos los elementos book bajo el elemento bookstore y que el valor del elemento price sea menor de 30:
doc("books.xml")/bookstore/book[price<30]
El XQuery anterior 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>
- Página anterior Introducción a XQuery
- Página siguiente FLWOR XQuery