Ut6 Xquery

Descargar como pdf o txt
Descargar como pdf o txt
Está en la página 1de 56

Curso de Formación

“Lenguajes de Marcas y Sistemas de Gestión de la Información”


Información”
Del 12 de Abril al 7 de Junio de 2010

Unidad V:
V:
XML: Lenguajes de Consulta
Xquery / XPath
Ponente:
Ponente:
José Luis Delgado Leal
Profesor del Departamento de Informática (Ciclos)
I E S “Juan
I.E.S. Juan de la Cierva”
Cierva (Madrid)

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Contenidos de la Presentación
 XQuery

 XPath

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
¿Qué es XQuery?

 XQuery es el lenguaje de consulta para datos XML

 XQuery es a XML lo que SQL es a las Bases de Datos

 XQuery se basa en expresiones XPath

 XQuery se ha definido por parte de W3C

 XQuery está admitido por la mayoría de los motores de bases de datos (IBM,
(IBM
Oracle, Microsoft, etc.)

 XQuery pasará a ser un estándar de W3C standard y los desarrolladores podrán


estar seguros de este modo que su código podrá trabajar con diferentes
plataformas

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Consultas XML usando XQuery

 XQuery is un lenguaje que permite encontrar y extraer elementos y atributos


de un documento XML

 Podríamos hacer con XQuery una consulta de esta índolo, por poner un
ejemplo:”Obtener todos los CD’s con un precio inferior a 10€ de la colección de
CD’ss almacenada en un documento XML llamado CatalogoCD.xml
CD CatalogoCD xml”

 XQuery está basado en XPath

 XQuery 1.0 y XPath 2.0 comparten el mismo modelo de datos y soportan las
mismas funciones y operadores

 Si se conoce XPath, el paso a XQuery es inmediato

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Ejemplos de Uso de XQuery

 Las aplicaciones de XQuery son múltiples:

 Extracción de información para ser usada en un Web Service

 Generación de Informes de Resumen

 Transformación de datos XML a XHTML

 Búsqueda en documentos web de información relevante

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
XQuery como estándar

 XQuery podría considerarse ya como un estándar web

 XQuery es compatible con múltiples estándares W3C, como pueda ser XML,
Namespaces, XSLT, XPath y XML Schema

 Sin embargo, XQuery 1.0 no es todavía un Recomendación W3C


Recommendation (XQuery es en la actualidad un Working Draft)

 Afortunadamente, y con toda seguridad, XQuery será una recomendación


W3C en un futuro bastante cercano

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Un Ejemplo 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>

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Trabajar con XQuery: Expresiones XPath (I)

 XQuery usa funciones para extraer los datos de los documentos XML

 La ffunción doc()
() se emplea
p para
p poder
p abrir el fichero
f "books.xml“:

doc("books.xml")

 XQuery usa expresiones “path” (rutas) para navegar a traves de los diferentes
elementos de un documento XML

 La siguiente expresión se emplea para seleccionar todos los títulos


(elementos título) del fichero "books.xml":

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

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Trabajar con XQuery: Expresiones XPath (II)

 De este modo, /bookstore selecciona el elemento bookstore, /book selecciona


todos los elementos book bajo el elemento bookstore, y /title selecciona todos
los elementos title bajo cada uno de los elementos book

 La consulta XQuery anterior obtiene el siguiente resultado:

<title lang="en">Everyday Italian</title>


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

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Predicados en XQuery

 XQueryy usa p
predicados p
para limitar el número de datos que
q se extraen de un
documento XML

 El siguiente predicado permite seleccionar todos los elementos book bajo el


elemento bookstore que tienen un precio con un valor price inferior a 30:

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

 La consulta de arriba obtendrá lo siguiente:

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

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Expresiones FLWOR (I)

 Sea la siguiente expresión

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

 La expresión mostrada seleccionará todos los elementos title bajo los


elementos book que a su vez se encuentran bajo el elemento bookstore que
tienen un valor en el elemento price mayor a 30

 La siguiente expresión FLWOR realiza la misma función que la expresión path


mostrada arriba:

for $x in doc("books.xml")/bookstore/book
where $x/price>30
return $x/title

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Expresiones FLWOR (II)

 El resultado será:

<title lang=
lang="en">XQuery
en >XQuery Kick Start</title>
<title lang="en">Learning XML</title>

 Con FLWOR se pueden ordenar los resultados:

for $x in doc("books.xml")/bookstore/book
where $x/price>30
order by $x/title
return $x/title

 FLWOR es el acrónimo de "For,Let,Where,Order by,Return“

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Expresiones FLWOR (III)

 La cláusula for selecciona todos los elementos book bajo el elemento


bookstore y los coloca en una variable llamada $x

 La cláusula where selecciona sólo los elementos book con un valor en el


elemento price mayor de 30

 La cláusula order by define el tipo de ordenación


ordenación. Así,
Así indica que los
resultados sean ordenados por el elemento title

 La cláusula return especifica qué es lo que ha de devolverse


devolverse. En este caso
caso,
devuelve los elementos title

 El resultado de la expresión XQuery anterior es:

<title lang="en">Learning XML</title>


lang="en">XQuery
<title lang= en >XQuery Kick Start</title>

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Nodos en XQuery (I)

 En terminología XQuery, se pueden distinguir siete tipos de nodos:


 Elementos (element)
 Atributos (attribute)
 Texto (text)
 Nombre de espacio (namespace)
 Instrucción de Procesamiento (processing-instruction)
 Comentario (comment)
 Documento (root node)

 Los documentos XML se tratan como si fueran árboles compuestos por


diferentes nodos

 La raíz de ese árbol se le llama nodo documento (nodo document, o también


se conoce nodo root)

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Nodos en XQuery (II)

 Sea el siguiente documento XML: Nodo Documento

<?xml version="1.0" encoding="ISO-8859-1"?>


<bookstore> N d Atributo
Nodo At ib t
<book>
<title lang="en">Harry Potter</title>
<author>J K.
K Rowling</author>
<year>2005</year>
<price>29.99</price>
</book> Nodo
odo Elemento
le e to
</bookstore>

 Los valores atómicos son aquellos nodos que no tienen ni nodos hijos
colgando de él, ni cuelgan de nodos padres. Ejemplo de ello son los items: J K.
Rowling, "en“

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Relaciones entre Nodos en XQuery (I)

 Padres: cada elemento y atributo tiene un padre. En el ejemplo anterior, el


elemento book es el padre los elementos title, author, year y price:

<book>
<title>Harry Potter</title>
<author>JJ K. Rowling</author>
g /
<year>2005</year>
<price>29.99</price>
</book>
/

 Hijos: los nodos elemento pueden tener cero, uno o más hijos. En el ejemplo
anterior, title, author, yyear y p
price son todos hijos
j del elemento book

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Relaciones entre Nodos en XQuery (II)

 Siblings (hermanos): los nodos siblings o hermanos son aquellos que tienen
el mismo padre. Así, siguiendo con el ejemplo, los nodos title, author, year, y
price son todos nodos hermanos

 Los nodos además se dicen que tienen ascendientes y descendientes.

 Los nodos ascendientes son los nodos padres de un nodo, los padres de un
padre,, etc.
pad t Para
a a ttitle,
tl , lo
los ascendientes
a d t son o book
oo y bookstore
oo to

 Los nodos descendientes son los hijos, los hijos de los hijos, etc. Para
bookstore,, los descendientes son book,, title,, author,, yyear y p
price

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Reglas Básicas en XQuery (I)

 XQuery es sensible
bl a mayúsculas
l y minúsculas
l

 Cualquier elemento, atributo o variable de XQuery tiene que ser un


identificador
d f d válido
l d en XML

 Un valor string o cadena de XQuery puede estar contenido tanto en comillas


simples
i l como d dobles
bl

 Una variable XQuery se define con un símbolo $ seguido por un nombre. Por
ejemplo,
j l $bookstore
$b k

 Un comentario XQuery se inserta dentro de un limitador de inicio (: y un


d li it d de
delimitador d fin
fi :).) Por
P ejemplo,
j l (:
( Hola
H l :))

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Reglas Básicas en XQuery (II)

 Las expresiones condicionales


d l “if-then-else”
f h l se permiten en XQuery. Sea ell
siguiente ejemplo:

ffor $x in doc("books.xml")/bookstore/book
d (b k l )b k b k
return if ($x/@category="CHILDREN")
then <child>{data($x/title)}</child>
else
l <adult>{data($x/title)}</adult>
d l {d ($ i l )} d l

 Respecto a la sintáxis de "if-then-else", decir que los paréntesis de la


condición
di ió van alrededor
l d d d de lla expresión
ió que se usa como evaluación,
l ió y su uso
es obligatorio

 El uso d
de else
l es iigualmente
l t obligatorio,
bli t i aunque puede
d estar
t vacío
í y ser sólo
ól
un else ()

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Reglas Básicas en XQuery (III)

 El resultado de la expresión anterior será:

<adult>Everyday Italian</adult>
<child>Harry Potter</child>
<adult>Learning XML</adult>
<adult>XQuery Kick Start</adult>

 Existen dos formas de comparar valores en XQuery:


• Comparaciones Generales: =, !=,
! <,< <=,
< >,> >=
>
• Comparación de valores: eq, ne, lt, le, gt, ge

 No es lo mismo comparar con un método que con otro


otro, puesto que cada una
tiene una indicación específica

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Reglas Básicas en XQuery (IV)

 La diferencia entre los dos métodos de comparación se muestra a


continuación

$bookstore//book/@q > 10
$bookstore//book/@q gt 10

 La primera expresión devuelve true si cualquier atributo q tiene un valor


mayor que 10

 La segunda expresión devuelve true si hay un solo atributo q devuelto por la


expresión y su valor es mayor que 10. Si hay más de un atributo q devuelto, se
produce
d un error

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Añadir Elementos y Atributos al Resultado (I)

 Se pueden añadir elementos y atributos del documento de entrada (en


nuestro caso, books.xml) en el resultado:

for $x in doc(
doc("books
books.xml
xml")/bookstore/book/title
)/bookstore/book/title
order by $x
return $x

 Esta expresión incluirá tanto los elementos title como los atributos lang en el
resultado, obteniéndose algo de esta forma:

<title lang="en">Everyday Italian</title>


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

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Añadir Elementos y Atributos al Resultado (II)
 La expresión anterior devuelve los elementos title de la misma forma que
están descritos en el documento de entrada

 Ahora queremos añadir nuestros elementos y atributos al resultado.


Colocaremos esto en un HTML junto con más texto:

<html>
<body>
<h1>Bookstore</h1>
<ul>
{
for $x in doc("books.xml")/bookstore/book
order by $x/title
return<li>{data($x/title)}.Categoría:{data($x/@category)}</li>
}
</ul>
</body>
/body
</html>
Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Añadir Elementos y Atributos al Resultado (III)

 La expresión anterior generará un resultado como éste:

<html>
html
<body>
<h1>Bookstore</h1>
<ul>
ul
<li>Everyday Italian. Category: COOKING</li>
<li>Harry Potter. Category: CHILDREN</li>
<li>Learning
l ea g XML.
X Category:
Catego y WEB</li>
/l
<li>XQuery Kick Start. Category: WEB</li>
</ul>
</body>
/ y
</html>

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Añadir Elementos y Atributos al Resultado (IV)

 Ahora,
Ahora se quiere usar la categoría atributo como una clase atributo en una
lista HTML:

<html>
<body>
<h1>Bookstore</h1>
<ul>
{
for $x in doc("books.xml")/bookstore/book
order by $x/title
return <li class="{data($x/@category)}">{data($x/title)}</li>
}
</ul>
</body>
</html>

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Añadir Elementos y Atributos al Resultado (V)

 La expresión anterior generará un resultado como éste:

<html>
<body>
<h1>Bookstore</h1>
<ul>
<li class="COOKING">Everyday Italian</li>
<li class="CHILDREN">Harry Potter</li>
<li class
class="WEB">Learning
WEB >Learning XML</li>
<li class="WEB">XQuery Kick Start</li>
</ul>
</body>
</html>

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Selección y Filtrado de Elementos

 Las selecciones o filtrados de elementos se pueden hacer,


hacer como ya se ha
visto, con expresiones Path o con expresiones FLWOR. Por ejemplo:

for $x in doc(
doc("books
books.xml
xml")/bookstore/book
)/bookstore/book
where $x/price>30
order by $x/title
return $x/title

 Las diferentes cláusulas cumplen:


 for (opcional): hace que una una variable tome cada uno de los items
devueltos por la expresión in
 let (opcional): realiza asignaciones
 where (opcional): especifica un criterio
 order by (opcional): especifica el orden del resultado
 return: especifica qué se devuelve en el resultado

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
La Cláusula for (I)

 La cláusula for enlaza una variable con cada item que se devuelve por la
expresión in. Esta cláusula produce una iteración.

 Puede haber múltiples cláusulas for en una misma expresión

 Para conseguir una interación un determinado número de veces la palabra


reservada to.
to Por ejemplo:

for $x in (1 to 3)
return <test>{$x}</test>

produce el resultado:

<test>1</test>
<test>2</test>
<test>3</test>

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
La Cláusula for (II)

 La palabra reservada at permite contar la iteración:

for $x at $i in doc(
doc("books
books.xml
xml")/bookstore/book/title
)/bookstore/book/title
return <book>{$i}. {data($x)}</book>

devuelve el resultado:

<book>1. Everyday Italian</book>


<book>2 Harry Potter</book>
<book>2.
<book>3. XQuery Kick Start</book>
<book>4. Learning XML</book>

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
La Cláusula for (III)

 Se permite tambíén más de una expresión en una cláusula for. Para ello, se
separan los valores mediante comas:

for $x in (10,20), $y in (100,200)


return <test>x={$x} and y={$y}</test>

devuelve el resultado:

<test>x 10 and yy=100</test>


<test>x=10 100</test>
<test>x=10 and y=200</test>
<test>x=20 and y=100</test>
<test>x=20
<test>x 20 and yy=200</test>
200</test>

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
La Cláusula let

 La cláusula let permite hacer asignaciones de variables, permitiendo evitar el


tener que repetir la misma expresión varias veces

 La cláusula let no provoca una iteración:

let $x ::= (1 to 5)
return <test>{$x}</test>

produce el resultado:

<test>1 2 3 4 5</test>

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Las Cláusulas where y order by
 La cláusula where se usa para especificar uno o más criterios para el
resultado:

where $x/price>30 and $x/price<100

 La cláusula order by especifica el criterio de ordenación del resultado. Así,


para ordenar ejemplo por categoría y título:

for $x in doc("books.xml")/bookstore/book
order by $x/@category, $x/title
return $x/title

produciría el resultado:

<title lang="en">Harry Potter</title>


<title lang="en">Everyday Italian</title>
<title
title lang="en">Learning XML</title>
lang en Learning XML /title
<title lang="en">XQuery Kick Start</title>
Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
La Cláusula return

 La cláusula return indica qué es lo que se quiere devolver

for $x in doc("books.xml")/bookstore/book
return $x/title

produce como resultado:

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

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Funciones en XQuery (I)

 XQuery 1.0, XPath 2.0 y XSLT 2.0 comparten la misma biblioteca de funciones

 XQuery incluye unas 100 funciones propias. Se puede ver un listado en


http://www.w3.org/2005/02/xpath-functions

 Hay funciones de todo tipo: para valores tipo cadena, para valores
numéricos, para comparación de fechas y horas, para manipulación de nodo y
manejo
j de QName, para
p manipulaciones
p de secuencias, ppara valores
booleanos y muchas otras.

 El usuario p
puede definir
f sus p
propias
p ffunciones

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Funciones en XQuery (II)

 El prefijo
f j usado por defecto
f en el espacio de nombre de las funciones
f es ffn:.
Por ejemplo, fn:string()

 Sin embargo, esto no ocurre en el caso del nombre de las funciones, que no
necesitan emplear el prefijo cuando son llamadas.

 Una llamada a una función puede aparecer en el mismo sitio donde una
expresión pueda colocarse. Por ejemplo:

En un elemento
<name>{uppercase($booktitle)}</name>

 En el predicado de una expresión path


doc("books.xml")/bookstore/book[substring(title,1,5)='Harry']

 En una cláusula let


l $name := (substring($booktitle,1,4))
let b b k l

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Funciones en XQuery (III)
 Se pueden definir funciones de usuario

 Pueden definirse en una consulta (query) o en una biblioteca aparte. Para


ello, se emplea esta sintaxis:

declare function prefix:funct_name($param AS datatype) AS returnDatatype


{
((: ...aquí
q se coloca el código
g de la ffunción... :))
};

 Es obligatorio
g el uso de declare ffunction

 El nombre de la función tiene que tener un prefijo

 Los tipos de los datos de los parámetros son generalmente de los mismos
tipos definidos en el XML Schema

 El cuerpo de una función debe estar incluido entre llaves {}

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Funciones en XQuery (IV)

 Ejemplo
l de
d definición
d f d función
de f d usuario:
de

declare function local:minPrice


(
($price as xs:decimal,
d l $discount
d as xs:decimal)
d l) AS xs:decimal
d l
{
let $disc := ($price * $discount) div 100
return ($price
($ i - $disc)
$di )
};

( A continuación
(: i ió se muestra una llamada
ll d a la
l función
f ió :))

<minPrice>
{l l i P i ($b k i $book/discount)}
{local:minPrice($book/price, $b k di t)}
</minPrice>

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Biblioteca de Funciones (I):
A
Accessor F ti
Functions, E
Error & TTrace Functions
F ti
Función Descripción
fn:node-name(node) Returns the node-name of the argument node
Returns a Boolean value indicating whether the argument node is
fn:nilled(node)
nilled
fn:data(item.item,...) Takes a sequence of items and returns a sequence of atomic values
fn:base-uri() Returns the value of the base-uri property of the current or specified
fn:base-uri(node) node
fn:document-uri(node) Returns the value of the document-uri property for the specified node
fn:implicit-timezone() Returns the value of the implicit timezone
f d f lt ll ti ()
fn:default-collation() R t
Returns th
the value
l off th
the d
default
f lt collation
ll ti
fn:static-base-uri() Returns the value of the base-uri
f
fn:error()
()
Example: error(fn:QName(
error(fn:QName('http://example
http://example.com/test
com/test', 'err:toohigh')
err:toohigh ),
fn:error(error)
'Error: Price is too high')
fn:error(error,description)
Result: Returns http://example.com/test#toohigh and the string "Error:
fn:error(error,description,e
Price is too high" to the external processing environment
rror object)
rror-object
fn:trace(value, label) Used to debug queries
Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Biblioteca de Funciones (II):
F ti
Functions on Numerics
N i

Función Descripción
Returns the numeric value of the argument. The argument could be a
fn:number(arg) boolean, string, or node-set
Example: number(
number('100‘)
100 ) Result: 100
Returns the absolute value of the argument
fn:abs(num) Example: abs(3.14) Result: 3.14
Example:
p abs(-3.14)
( 3 4) Result: 33.144
Returns the smallest integer that is greater than the number argument
fn:ceiling(num)
Example: ceiling(3.14) Result: 4
Returns the largest integer that is not greater than the number argument
f fl (num)
fn:floor(
Example: floor(3.14) Result: 3
Rounds the number argument to the nearest integer
fn:round(num)
Example:
p round(3.14)
(3 4) Result: 3
Example: round-half-to-even(0.5) Result: 0
fn:round-half-to-even() Example: round-half-to-even(1.5) Result: 2
Example: round-half-to-even(2.5) Result: 2

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Biblioteca de Funciones (III):
F ti
Functions on Strings
St i (I)

Función Descripción
Returns the string value of the argument. The argument could
fn:string(arg)
be a number, boolean, or node-set
p string(314)
Example: g(3 4) Result: "314”
3 4
Returns a string from a sequence of code points
fn:codepoints-to-string(int, int, ...)
Example: codepoints-to-string(84, 104, 233, 114, 232, 115, 101)
Result: 'Thérèse‘
Returns a sequence of code points from a string
fn:string-to-codepoints(string)
Example: string-to-codepoints("Thérèse")
Result: 84, 104, 233, 114, 232, 115, 101
Returns true if the value of comp1 is equal to the value of
fn:codepoint-equal(comp1,comp2) comp2, according to the Unicode code point collation
(http://www.w3.org/2005/02/xpath-
functions/collation/codepoint) otherwise it returns false
functions/collation/codepoint),
Returns -1 if comp1 is less than comp2, 0 if comp1 is equal to
fn:compare(comp1,comp2) comp2, or 1 if comp1 is greater than comp2 (according to the
fn:compare(comp1,comp2,collation) rules of the collation that is used)
Example: compare('ghi', 'ghi‘) Result: 0

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Biblioteca de Funciones (IV):
F ti
Functions on Strings
St i (II)
Función Descripción
Returns the
h concatenation off the h strings
fn:concat(string,string,...)
Example: concat('XPath ','is ','FUN!‘) Result: 'XPath is FUN!’
Returns a string created by concatenating the string arguments
and using the sep argument as the separator
Example: string-join(('We', 'are', 'having', 'fun!'), ' ')
fn:string-join((string,string,...),sep)
Result: ' We are having fun! '
Example: string-join(('We', 'are', 'having', 'fun!'))
Result: 'Wearehavingfun!'
Example:string-join((), 'sep‘) Result: ‘’
Returns the substring from the start position to the specified
(string,start,len
ffn:substring(
b l ) l th Index
length. I d off the
th first
fi t character
h t is
i 1. If length
l th isi omitted
itt d it
fn:substring(string,start) returns the substring from the start position to the end
Example: substring('Beatles',1,4) Result: 'Beat'
Example:
p substring('Beatles',2)
g( , ) Result: 'eatles’
Returns the length of the specified string. If there is no string
fn:string-length(string) argument it returns the length of the string value of the current
fn:string-length() node
l string-length('Beatles‘)
Example: l h( l ‘) Result: l 7

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Biblioteca de Funciones (V):
F ti
Functions on Strings
St i (III)

Función Descripción
Removes leading and trailing spaces from the specified string,
and replaces all internal sequences of white space with one
fn:normalize-space(string)
and returns the result. If there is no string argument it does the
f
fn:normalize-space()
li ()
same on the current node
Example: normalize-space(' The XML ‘) Result: 'The XML’
f
fn:normalize-unicode()
()
Converts the string argument to upper-case
fn:upper-case(string) Example: upper-case('The XML‘) Result: 'THE XML'

Converts the string argument to lower-case


fn:lower-case(string)
Example: lower-case('The XML‘) Result: 'the xml’
Converts string1 by replacing the characters in string2 with the
characters in string3
fn:translate(string1,string2,string3) Example: translate('12:30','30','45‘) Result: '12:45'
Example: translate('12:30','03','54‘) Result: '12:45'
translate('12:30'
Example: translate( 12:30 ,'0123'
0123 ,'abcd‘)
abcd ) Result: 'bc:da’
bc:da

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Biblioteca de Funciones (VI):
F ti
Functions on Strings
St i (IV)
Función Descripción
Example: escape-uri("http://example.com/test#car", true())
Result: "http%3A%2F%2Fexample.com%2Ftest#car"
Example: escape-uri("http://example.com/test#car", false())
uri(stringURI,esc
fn:escape-uri(
fn:escape stringURI,esc-res
res)
R lt "htt
Result: "http://example.com/test#car"
// l /t t "
Example: escape-uri ("http://example.com/~bébé", false())
Result: "http://example.com/~b%C3%A9b%C3%A9”
Returns true if string1 contains string2
string2, otherwise it returns
fn:contains(string1,string2) false
Example: contains('XML','XM‘) Result: true
Returns true if string1 starts with string2, otherwise it returns
fn:starts-with(string1,string2) false
Example: starts-with('XML','X') Result: true
Returns true if string1 ends with string2, otherwise it returns
fn:ends-with(string1,string2) false
Example: ends-with('XML','X') Result: false
Returns the start of string1 before string2 occurs in it
g f (string1,string2
ffn:substring-before( g , g )
E l substring-before('12/10','/‘)
Example: b t i g b f (' / ' '/‘) Result:
R lt '12’
' ’

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Biblioteca de Funciones (VII):
F ti
Functions on Strings
St i (V)

Función Descripción
Returns the remainder of string1 after string2 occurs in it
fn:substring-after(string1,string2)
Example: substring-after('12/10','/‘)
substring after( 12/10 , / ) Result: '10’
10
Returns true if the string argument matches the pattern,
fn:matches(string,pattern) otherwise, it returns false
Example: matches("Merano", "ran“) Result: true
Returns a string that is created by replacing the given pattern
with the replace argument
fn:replace(string,pattern,replace) Example: replace("Bella Italia", "l", "*“) Result: 'Be**a Ita*ia'
E
Example:
l replace("Bella
l ("B ll It Italia",
li " "l",
"l" "“) Result:
R lt 'B 'Bea Itaia'
It i '

Example: tokenize("XPath is fun", "\s+“)


fn:tokenize(string,pattern)
Result: ("XPath"
( XPath , "is"
is , "fun“)
fun )
fn:resolve-uri(relative,base)

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Biblioteca de Funciones (VIII):
F ti
Functions on Booleans
B l

Función Descripción
fn:boolean(arg) Returns a boolean value for a number,
number string
string, or node
node-set
set
The argument is first reduced to a boolean value by applying
the boolean() function. Returns true if the boolean value is
fn:not(arg)
false and false if the boolean value is true
false,
Example: not(true()) Result: false
Returns the boolean value true
fn:true()
Example:
p true()() Result: true
Returns the boolean value false
fn:false()
Example: false() Result: false

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Biblioteca de Funciones (IX):
F ti
Functions on Durations,
D ti D t and
Dates d Times
Ti (I)
Función Descripción
fn:dateTime(date,time
date time) Converts the arguments to a date and a time
Returns an integer that represents the years component
fn:years-from-duration(datetimedur) in the canonical lexical representation of the value of the
argument
Returns an integer that represents the months
fn:months-from-duration(datetimedur) component in the canonical lexical representation of the
value of the argument
Returns an integer that represents the days component in
fn:days-from-duration(datetimedur) the canonical lexical representation of the value of the
argument
Returns an integer that represents the hours component
fn:hours-from-duration(datetimedur) in the canonical lexical representation of the value of the
argument
Returns an integer that represents the minutes
fn:minutes-from-duration(datetimedur) component in the canonical lexical representation of the
value of the argument
Returns a decimal that represents the seconds
fn:seconds-from-duration(datetimedur) component in the canonical lexical representation of the
value of the argument
Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Biblioteca de Funciones (X):
F ti
Functions on Durations,
D ti D t and
Dates d Times
Ti (II)

Función
F ió Descripción
D i ió
Returns an integer that represents the year component in
the localized value of the argument
fn:year-from-dateTime(datetime)
Example: year-from-dateTime(xs:dateTime(
year-from-dateTime(xs:dateTime("2005-01-
2005-01-
10T12:30-04:10")) Result: 2005
Returns an integer that represents the month component in
the localized value off the argument
g
f d t Ti (datetime
fn:month-from-dateTime(
th f d t ti )
Example: month-from-dateTime(xs:dateTime("2005-01-
10T12:30-04:10")) Result: 01
Returns an integer that represents the day component in
the localized value of the argument
fn:day-from-dateTime(datetime)
Example: day-from-dateTime(xs:dateTime("2005-01-
10T12:30-04:10")) Result: 10
Returns
R t an iinteger
t g that
th t represents
t the
th hours
h componentt in
i
the localized value of the argument
fn:hours-from-dateTime(datetime)
Example: hours-from-dateTime(xs:dateTime("2005-01-
10T12:30-04:10"))
3 4 )) Result: 12

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Biblioteca de Funciones (XI):
F ti
Functions on Durations,
D ti D t and
Dates d Times
Ti (III)
Función Descripción
Returns an integer that represents the minutes component
in the localized value of the argument
fn:minutes-from-dateTime(datetime)
Example: minutes-from-dateTime(xs:dateTime("2005-01-
10T12:30-04:10"))
10T12:30 04:10 )) Result: 30
Returns a decimal that represents the seconds component
fn:seconds-from-dateTime(datetime) in the localized value of the argument
p seconds-from-dateTime(xs:dateTime("2005-01-
Example: f ( ( 5
10T12:30:00-04:10")) Result: 0
fn:timezone-from-dateTime(datetime)
Returns the time zone component of the argument if any

Returns an integer that represents the year in the localized


value of the argument
fn:year-from-date(date)
Example: year-from-date(xs:date("2005-04-23"))
Result: 2005
Returns an integer that represents the month in the
localized value of the argument
fn:month-from-date(date)
Example: month-from-date(xs:date("2005-04-23"))
month from date(xs:date( 2005 04 23 ))
Result: 4

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Biblioteca de Funciones (XII):
F ti
Functions on Durations,
D ti D t and
Dates d Times
Ti (IV)
Función p
Descripción
Returns an integer that represents the day in the localized
fn:day-from-date(date) value of the argument
Example: day-from-date(xs:date("2005-04-23"))
Result: 23
fn:timezone-from-date(date) Returns the time zone component of the argument if any
g that represents
Returns an integer p the hours component
p in
the localized value of the argument
fn:hours-from-time(time)
Example: hours-from-time(xs:time("10:22:00"))
Result: 10
h represents the
Returns an integer that h minutes component
in the localized value of the argument
fn:minutes-from-time(time)
Example: minutes-from-time(xs:time("10:22:00"))
Result: 22
Returns an integer that represents the seconds component
in the localized value of the argument
fn:seconds-from-time(time)
Example: seconds-from-time(xs:time("10:22:00"))
Result: 0

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Biblioteca de Funciones (XIII):
F ti
Functions on Durations,
D ti D t and
Dates d Times
Ti (V)
(V). QNames
QN
Función Descripción
fn:timezone-from-time(time) Returns the time zone component of the argument if any
fn:adjust-dateTime-to- If the timezone argument is empty, it returns a dateTime
timezone(datetime,timezone) without a timezone. Otherwise, it returns a dateTime with a
timezone
fn:adjust-date-to- If the timezone argument is empty, it returns a date
timezone(date,timezone) without a timezone. Otherwise, it returns a date with a
timezone
fn:adjust-time-to- If the timezone argument is empty, it returns a time
timezone(time,timezone) without a timezone. Otherwise, it returns a time with a
timezone
fn:QName()
fn:local-name-from-QName()
f
fn:namespace-uri-from-QName()
if QN ()
fn:namespace-uri-for-prefix()
ffn:in-scope-prefixes()
p p f ()
fn:resolve-QName()

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Biblioteca de Funciones (XIV):
F ti
Functions on Nodes
N d & Sequences
S (I)
Función Descripción
fn:name()
f () Returns the
h name off the
h current node
d or the
h ffirst node
d in
fn:name(nodeset) the specified node set
fn:local-name() Returns the name of the current node or the first node in
fn:local-name(nodeset) the specified node set - without the namespace prefix
fn:namespace-uri() Returns the namespace URI of the current node or the first
fn:namespace-uri(nodeset) node in the specified node set
Returns true if the language of the current node matches
the language of the specified language
fn:lang(lang) Example: Lang("en") is true for <p xml:lang="en">...</p>
Example: Lang("de") is false for <p xml:lang="en">...</p>
Returns the root of the tree to which the current node or
ffn:root()
t()
the specified belongs. This will usually be a document
fn:root(node)
node
Returns the positions within the sequence of items that are
equall to the
h searchitem
h argument
fn:index-of((item,item,...),searchitem) Example: index-of ((15, 40, 25, 40, 10), 40) Result: (2, 4)
Example: index-of (("a", "dog", "and", "a", "duck"), "a")
Result (1
(1, 4)
Example: index-of ((15, 40, 25, 40, 10), 18) Result: ()

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Biblioteca de Funciones (XV):
F ti
Functions on Nodes
N d & Sequences
S (II)
Función Descripción
Returns a new sequence constructed from the value of
the item arguments - with the item specified by the
position argument removed
Example: remove(("ab", "cd", "ef"), 0)
fn:remove((item,item,...),position) Result: ("ab", "cd", "ef")
Example: remove(("ab", "cd", "ef"), 1)
Result: ("cd"
( cd , "ef")
ef )
Example: remove(("ab", "cd", "ef"), 4)
Result: ("ab", "cd", "ef“)
Returns true if the value of the arguments IS an empty
fn:empty(item,item,...) sequence, otherwise it returns false
Example: empty(remove(("ab", "cd"), 1)) Result: false
Returns true if the value of the arguments IS NOT an
fn:exists(item,item,...
item item ) empty sequence, otherwise it returns false
Example: exists(remove(("ab"), 1)) Result: false
Returns only distinct (different) values
ffn:distinct-values((((item,item,...),collation
, , ), )
E l distinct-values((1,
Example: di ti t l (( 2, 3, 1, 2)) )) R lt ((1, 2, 3))
Result:

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Biblioteca de Funciones (XVI):
F ti
Functions on Nodes
N d & Sequences
S (III)
Función Descripción
Returns a new sequence constructed from the value of
the item arguments - with the value of the inserts
argument inserted in the position specified by the pos
argument
Example: insert-before(("ab", "cd"), 0, "gh")
Result: ("gh", "ab", "cd")
fn:insert-before((item,item,...),pos,inserts) Example: insert-before(("ab"
insert before(( ab , "cd")
cd ), 1,
1 "gh")
gh )
Result: ("gh", "ab", "cd")
Example: insert-before(("ab", "cd"), 2, "gh")
Result: ("ab", "gh", "cd")
Example:
l insert-before(("ab",
b f (( b "cd"), d ) 5, "gh")
h)
Result: ("ab", "cd", "gh")
Returns the reversed order of the items specified
Example: reverse(("ab",
reverse(("ab" "cd",
"cd" "ef"))
fn:reverse((item,item,...)) Result: ("ef", "cd", "ab")
Example: reverse(("ab"))
Result: (("ab“))

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Biblioteca de Funciones (XVII):
F ti
Functions on Nodes
N d & Sequences
S (IV) Test
(IV). T t off Cardinality
C di lit

Función Descripción
Returns a sequence of items from the position specified
by the start argument and continuing for the number of
p f byy the len argument.
items specified g The first
f item is
located at position 1
fn:subsequence((item,item,...),start,len) Example: subsequence(($item1, $item2, $item3,...), 3)
Result: ($item3, ...)
Example: subsequence(($item1
subsequence(($item1, $item2,
$item2 $item3,
$item3 ...),) 2,
2 2)
Result: ($item2, $item3)
fn:unordered((item,item,...)) Returns the items in an implementation dependent order
Returns the
R h argument if it i contains
i zero or one items,
i
fn:zero-or-one(item,item,...)
otherwise it raises an error
Returns the argument if it contains one or more items,
ffn:one-or-more((item,item,...
, , )
other ise it raises an error
otherwise
Returns the argument if it contains exactly one item,
fn:exactly-one(item,item,...)
otherwise it raises an error

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Biblioteca de Funciones (XVIII):
A
Aggregatet Functions
F ti
Función Descripción
fn:count((item,
(item item,...)
item )) Returns the count of nodes
Returns the average of the argument values
fn:avg((arg, arg,...)) Example: avg((1,2,3)) Result: 2
Returns the argument that is greater than the others
f ((arg,
fn:max( ( arg,...))) Example: max((1,2,3)) Result: 3 Example: max(('a', 'k')) Result: 'k’
Returns the argument that is less than the others
fn:min((arg, arg,...)) Example: min((1,2,3)) Result: 1 Example: min(('a', 'k')) Result: 'a’
Returns the sum of the numeric value of each node in the specified
fn:sum(arg, arg,...)
node-set
Returns a sequence of element nodes that have an ID value equal
fn:id((string,string,...),node)
to the
h value
l off one or more off the
h values
l specified
f d in the
h string(s)
Returns a sequence of element or attribute nodes that have an
fn:idref((string,string,...),node) IDREF value equal to the value of one or more of the values
specified
ifi d iin th
the string
t i argumentt
fn:doc-available(URI) Returns true if the doc() function returns a document node,
otherwise it returns false
fn:collection()
fn:collection(string)
Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Biblioteca de Funciones (XIX):
C t t Functions
Context F ti

Función
ó Descripción
ó
Returns the index position of the node that is currently being processed
fn:position() Example: //book[position()<=3]
Result: Selects the first three book elements
Returns the number of items in the processed node list
fn:last() Example: //book[last()]
Result: Selects the last book element
fn:current-dateTime() Returns the current dateTime (with timezone)
fn:current-date()
fn:current date() Returns the current date (with timezone)
fn:current-time() Returns the current time (with timezone)
fn:implicit-timezone() Returns the value of the implicit timezone
fn:default-collation() Returns the value of the default collation
fn:static-base-uri() Returns the value of the base-uri

Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”

También podría gustarte

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy