Ut6 Xquery
Ut6 Xquery
Ut6 Xquery
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 está admitido por la mayoría de los motores de bases de datos (IBM,
(IBM
Oracle, Microsoft, etc.)
Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Consultas XML usando XQuery
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 1.0 y XPath 2.0 comparten el mismo modelo de datos y soportan las
mismas funciones y operadores
Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Ejemplos de Uso de XQuery
Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
XQuery como estándar
XQuery es compatible con múltiples estándares W3C, como pueda ser XML,
Namespaces, XSLT, XPath y XML Schema
Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Un Ejemplo XML
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
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)
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
doc("books.xml")/bookstore/book[price<30]
<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)
doc("books.xml")/bookstore/book[price>30]/title
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>
for $x in doc("books.xml")/bookstore/book
where $x/price>30
order by $x/title
return $x/title
Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Expresiones FLWOR (III)
Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Nodos en XQuery (I)
Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Nodos en XQuery (II)
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)
<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 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
Una variable XQuery se define con un símbolo $ seguido por un nombre. Por
ejemplo,
j l $bookstore
$b k
Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Reglas Básicas en XQuery (II)
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
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)
<adult>Everyday Italian</adult>
<child>Harry Potter</child>
<adult>Learning XML</adult>
<adult>XQuery Kick Start</adult>
Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
Reglas Básicas en XQuery (IV)
$bookstore//book/@q > 10
$bookstore//book/@q gt 10
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)
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:
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
<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)
<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)
<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
for $x in doc(
doc("books
books.xml
xml")/bookstore/book
)/bookstore/book
where $x/price>30
order by $x/title
return $x/title
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.
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)
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:
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:
devuelve el resultado:
Curso de Formación:
Formación: “Lenguajes de Marcas y Sistemas de Gestión de Información”
La Cláusula let
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:
for $x in doc("books.xml")/bookstore/book
order by $x/@category, $x/title
return $x/title
produciría el resultado:
for $x in doc("books.xml")/bookstore/book
return $x/title
<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
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>
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
Es obligatorio
g el uso de declare ffunction
Los tipos de los datos de los parámetros son generalmente de los mismos
tipos definidos en el XML Schema
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
( 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'
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 '
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
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”