8. Datos Semiestructurados8.1 IntroducciónDatos semiestructurados:
8.2 XML: Extensible Markup Language.8.2.1 Definición
|
Expression |
Abbreviation |
Es 2 cosas:
Transformation Language (XSLT)
Formatting Language (XSL Formatting Objects)
XSLT transforma un documento XML en otro documento XML
XSLFO da formato y estilo a un documento de diversas maneras
XSLT - http://www.w3.org/TR/xslt
Para poder hacer una tranformación se necesita:
Documento XML ha ser transformado (students.xml)
Style Sheet que especifica la transformación (students.xsl)
XML Document (students.xml)
<?xml version="1.0"?>
<course>
<name id="csci_2962">Programming XML in Java</name>
<teacher id="jp">John Punin</teacher>
<student id="js">
<name>John Smith</name>
<hw1>30</hw1>
<hw2>70</hw2>
<project>11.</project>
<final>11.</final>
</student>
<student id="gl">
<name>George Lucas</name>
<hw1>11.</hw1>
<hw2>90</hw2>
<project>100</project>
<final>40</final>
</student>
<student id="lr">
<name>Elizabeth Roberts</name>
<hw1>60</hw1>
<hw2>95</hw2>
<project>50</project>
<final>90</final>
</student>
</course>
XSLT Style Sheet (students.xsl)
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="course">
<HTML>
<HEAD>
<TITLE>Name of students</TITLE>
</HEAD>
<BODY>
<xsl:apply-templates select="student"/>
</BODY>
</HTML>
</xsl:template>
<xsl:template match="student">
<P>
<xsl:value-of select="name"/>
</P>
</xsl:template>
</xsl:stylesheet>
En el servidor - Debe existir un programa, ej Java Servlet, que utiliza la hoja de estilo para transformarlo automáticamente enviarlo al cliente
En el cliente - Un programa, ej un navegador, puede hacer la tranformación en base a la especificación de la hoja de estilo
<?xml-stylesheet href="students.xsl" type="text/xsl"?>
<course>... </course>
Con un programa independiente - Programas o aplicaciones que realizan todas las acciones con algun objetivo en particular
Oracle XML parser for Java
http://technet.oracle.com/tech/xml/parser_java2/
Sablotron
http://www.gingerall.com/charlie-bin/get/webGA/act/sablotron.act
Microsoft XML Parser
http://msdn.microsoft.com/downloads/webtechnology/xml/msxml.asp
Xalan Java
http://xml.apache.org/xalan-j/index.html
Procesando hojas de estilo
A través de un browserUn documento xml puede hacer referencia a una hoja de estilo para que un navegador o visualizador pueda formatear dicho documento y desplegarlo correctamente
<?xml-stylesheet type="text/xsl" href="foo.xsl"?> |
Nota: Algunos browsers no tienen asociada la extensión/mimetype
xsl marcarán un error, la solución es nombrar la hoja de estilo
con extensión xml.
java -classpath "xalan.jar" org.apache.xalan.xslt.Process -IN students.xml -XSL students.xsl -OUT students.html
1:import java.io.FileNotFoundException; 2:import java.io.FileWriter; 3:import java.io.StringWriter; 4:import java.io.IOException; 5:import javax.xml.transform.Transformer; 6:import javax.xml.transform.TransformerConfigurationException; 7:import javax.xml.transform.TransformerException; 8:import javax.xml.transform.TransformerFactory; 9:import javax.xml.transform.stream.StreamResult; 10:import javax.xml.transform.stream.StreamSource; 11: 12:public class SimpleTransform 13:{ 14:public static void main(String[] args) 15: throws TransformerException, TransformerConfigurationException, 16: FileNotFoundException, IOException 17:{ 18: 19: 20: TransformerFactory tFactory = TransformerFactory.newInstance(); 21: 22: Transformer transformer = tFactory.newTransformer(new StreamSource("students.xsl")); 23: 24: String out=new String(); 25: StringWriter sw=new StringWriter(); 26: transformer.transform(new StreamSource("students.xml"),new StreamResult(sw)); 27: out=sw.toString(); 28: System.out.println(out); 29: 30:} 31:} 32: |
<HTML> <HEAD> <TITLE>Name of students</TITLE> </HEAD> <BODY> <P>John Smith</P> <P>George Lucas</P> <P>Elizabeth Roberts</P> </BODY> </HTML>
Documentos XML son árboles de nodos
Tipos de Nodos
Document root
Start of document
Attribute - Value of an attribute
Comment - Text of a comment
Element - Character data in the element
Namespace - Namespace's URI
Processing Instruction - Text of processing instruction
Text - Hold the text of the node
La hoja de estilo es también un documento XML
xsl:stylesheet - elemento raíz
xsl:template - cómo tranformar el nodo seleccionado
match - atributo para seleccionar el nodo (usando XPath)
"/" - nodo raíz del documento XML de entrada (que será transformado)
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
.
.
.
</xsl:template>
</xsl:stylesheet>
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<HTML>
<HEAD>
<TITLE>
New XML Document
</TITLE>
</HEAD>
<BODY>
Programming XML in Java
</BODY>
</HTML>
</xsl:template>
</xsl:stylesheet>
Aplica los cambios (templates) a los hijos del nodo seleccionado
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<HTML>
<HEAD>
<TITLE>Name of students</TITLE>
</HEAD>
<BODY>
<xsl:apply-templates/>
</BODY>
</HTML>
</xsl:template>
<xsl:template match="course">
<xsl:apply-templates select="student"/>
</xsl:template>
<xsl:template match="student">
<P>
Student Data
</P>
</xsl:template>
</xsl:stylesheet>
Obtener el valor de los nodos y poder escribirlo en archivo de salida
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<HTML>
<HEAD>
<TITLE>Name of students</TITLE>
</HEAD>
<BODY>
<xsl:apply-templates/>
</BODY>
</HTML>
</xsl:template>
<xsl:template match="course">
<xsl:apply-templates select="student"/>
</xsl:template>
<xsl:template match="student">
<P>
<xsl:value-of select="name"/>
</P>
</xsl:template>
</xsl:stylesheet>
HTML output file:
<HTML>
<HEAD>
<TITLE>Name of students</TITLE>
</HEAD>
<BODY>
<P>John Smith</P>
<P>George Lucas</P>
<P>Elizabeth Roberts</P>
</BODY>
</HTML>
Select attribute solo selecciona el primer nodo (elemento) que cumpla con el criterio
En este caso el student solo tiene un tag "name", pero si tuviera varios, solo obtendríamos el primero
Si se quiere tener múltiples selecciones, recuperar los demás "name" contenidos en un nodo entonces se debe utilizar xsl:for-each
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<HTML>
<HEAD>
<TITLE>Name of students</TITLE>
</HEAD>
<BODY>
<xsl:apply-templates/>
</BODY>
</HTML>
</xsl:template>
<xsl:template match="course">
<xsl:apply-templates select="student"/>
</xsl:template>
<xsl:template match="student">
<xsl:for-each select="name">
<P> <xsl:value-of select="."/> </P>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
Encontrando el nodo raíz:
<xsl:template match="/">
...
</xsl:template>
Encontrando elementos:
<xsl:template match="student">
...
</xsl:template>
Encontrando elementos hijos:
<xsl:template match="course/student">
...
</xsl:template>
<xsl:template match="course/*/name">
...
</xsl:template>
Encontrando hijos descendientes:
<xsl:template match="course//name">
...
</xsl:template>
Ejemplo:
XSL Style Sheet
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<HTML>
<HEAD>
<TITLE>Names</TITLE>
</HEAD>
<BODY>
<xsl:apply-templates/>
</BODY>
</HTML>
</xsl:template>
<xsl:template match="text()">
</xsl:template>
<xsl:template match="course/name">
<H2>
<xsl:value-of select="."/>
</H2>
</xsl:template>
<xsl:template match="course/*/name">
<H3>
<xsl:value-of select="."/>
</H3>
</xsl:template>
</xsl:stylesheet>
HTML output file:
<HTML>
<HEAD>
<TITLE>Names</TITLE>
</HEAD>
<BODY>
<H2>Programming XML in Java</H2>
<H3>John Smith</H3>
<H3>George Lucas</H3>
<H3>Elizabeth Roberts</H3>
</BODY>
</HTML>
Encontrando atributos
Colocar el prefijo @ a los nombres de atributos
Ejemplo:
XML Document Input (figures.xml)
<?xml version="1.0"?>
<figures>
<circle x="20" y="10" r="20"/>
<rectangle x="-3" y="4" w="5" h="36"/>
<ellipse x="-5" y="6" w="30" h="50"/>
<rectangle x="7" y="23" w="58" h="45"/>
<circle x="-2" y="5" r="35"/>
<ellipse x="-10" y="-8" w="45" h="30"/>
</figures>
XSL Style Sheet
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<HTML>
<HEAD><TITLE>Figures</TITLE></HEAD>
<BODY>
<xsl:apply-templates/>
</BODY>
</HTML>
</xsl:template>
<xsl:template match="figures">
<TABLE>
<TR><TD>X</TD><TD>Y</TD></TR>
<xsl:apply-templates select="circle"/>
</TABLE>
</xsl:template>
<xsl:template match="circle">
<TR> <TD><xsl:value-of select="@x"/></TD>
<TD><xsl:value-of select="@y"/></TD> </TR>
</xsl:template>
</xsl:stylesheet>
HTML output file:
<HTML>
<HEAD>
<TITLE>Figures</TITLE>
</HEAD>
<BODY>
<TABLE>
<TR>
<TD>X</TD><TD>Y</TD>
</TR>
<TR>
<TD>20</TD><TD>10</TD>
</TR>
<TR>
<TD>-2</TD><TD>5</TD>
</TR>
</TABLE>
</BODY>
</HTML>
Matching Comments:
<xsl:template match="comment()">
...
</xsl:template>
Matching Text Nodes:
<xsl:template match="text()">
...
</xsl:template>
Using the OR operator:
Example: Generar una lista de los nombres de estudiantes y las
calificaciones de sus proyectos
XSL Style Sheet
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="course">
<HTML>
<HEAD>
<TITLE>Projects Grades</TITLE>
</HEAD>
<BODY>
<TABLE>
<xsl:apply-templates select="student"/>
</TABLE>
</BODY>
</HTML>
</xsl:template>
<xsl:template match="text()">
</xsl:template>
<xsl:template match="student">
<TR><xsl:apply-templates/></TR>
</xsl:template>
<xsl:template match="name | project">
<TD><xsl:value-of select="."/></TD>
</xsl:template>
</xsl:stylesheet>
HTML output file:
<HTML>
<HEAD>
<TITLE>Projects Grades</TITLE>
</HEAD>
<BODY>
<TABLE>
<TR>
<TD>John Smith</TD><TD>11.</TD>
</TR>
<TR>
<TD>George Lucas</TD><TD>100</TD>
</TR>
<TR>
<TD>Elizabeth Roberts</TD><TD>50</TD>
</TR>
</TABLE>
</BODY>
</HTML>
Validando con []
Valida cuándo una condición es "true", por ejemplo:
elemento "student" con un elemento hijo "name"
<xsl:template match="student[name]">
Cualquier elemento que tenga un subelemento "name"
<xsl:template match="*[name]">
Elemento "student" que tenga los subelementos "hw1"
o "hw2"
<xsl:template match="student[hw1 | hw2]">
Example: Nombre del estudiante con id 'js'
XSL Style Sheet:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="course">
<NAME>
<xsl:apply-templates select="student"/>
</NAME>
</xsl:template>
<xsl:template match="text()">
</xsl:template>
<xsl:template match="student[@id = 'js']">
<xsl:value-of select="name"/>
</xsl:template>
</xsl:stylesheet>
1. <xsl:template match="/ | *">
<xsl:apply-templates/>
</xsl:template>
2. <xsl:template match="text()">
<xsl:value-of select="."/>
</xsl:template>
3. <xsl:template match="@">
<xsl:value-of select="."/>
</xsl:template>
4. <xsl:template match="comment()"/>
5. <xsl:template match="processing-instruction()"/>
Style-sheet sin reglas:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
</xsl:stylesheet>
Output File (aplicado a students.xml):
<?xml version="1.0" encoding="UTF-8"?>
Programming XML in Java
John Punin
John Smith
30
70
11.
11.
George Lucas
11.
90
100
40
Elizabeth Roberts
60
95
50
90
Convertir el texto de algunos elementos en atributos de otros elementos
XSL Style Sheet:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="course">
<STUDENTS>
<xsl:apply-templates select="student"/>
</STUDENTS>
</xsl:template>
<xsl:template match="student">
<STUDENT NAME="{name}"
HW1="{hw1}"
HW2="{hw2}"
PROJECT="{project}"
FINAL="{final}"/>
</xsl:template>
</xsl:stylesheet>
XML output file:
<?xml version="1.0" encoding="UTF-8"?>
<STUDENTS>
<STUDENT FINAL="11." PROJECT="11." HW2="70" HW1="30" NAME="John Smith"/>
<STUDENT FINAL="40" PROJECT="100" HW2="90" HW1="11." NAME="George Lucas"/>
<STUDENT FINAL="90" PROJECT="50" HW2="95" HW1="60" NAME="Elizabeth Roberts"/>
</STUDENTS>
Para crear nuevos elementos se utiliza<xsl:element>
XML document (animals.xml):
<?xml version="1.0"?>
<animals>
<animal name="dog" class="mammal" legs="4"/>
<animal name="shark" class="fish" legs="0"/>
<animal name="chicken" class="bird" legs="2"/>
</animals>
Transformarlo al XML document (pets.xml):
<?xml version="1.0" encoding="UTF-8"?>
<pets>
<mammal>
<name>dog</name>
<legs>4</legs>
</mammal>
<fish>
<name>shark</name>
<legs>0</legs>
</fish>
<bird>
<name>chicken</name>
<legs>2</legs>
</bird>
</pets>
XSL Style Sheet:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:template match="animals">
<pets>
<xsl:apply-templates select="animal"/>
</pets>
</xsl:template>
<xsl:template match="animal">
<xsl:element name="{@class}">
<name><xsl:value-of select="@name"/></name>
<legs><xsl:value-of select="@legs"/></legs>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
Para crear nuevos atributos se utiliza <xsl:attribute>
XML document (animals.xml):
<?xml version="1.0"?>
<animals>
<animal name="dog" class="mammal" legs="4"/>
<animal name="shark" class="fish" legs="0"/>
<animal name="chicken" class="bird" legs="2"/>
</animals>
Transformarlo al XML document (pets.xml):
<?xml version="1.0" encoding="UTF-8"?>
<pets>
<mammal name="dog" legs="4"/>
<fish name="shark" legs="0"/>
<bird name="chicken" legs="2"/>
</pets>
XSL Style Sheet:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:template match="animals">
<pets>
<xsl:apply-templates select="animal"/>
</pets>
</xsl:template>
<xsl:template match="animal">
<xsl:element name="{@class}">
<xsl:attribute name="name">
<xsl:value-of select="@name"/>
</xsl:attribute>
<xsl:attribute name="legs">
<xsl:value-of select="@legs"/>
</xsl:attribute>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
<xsl:copy>para copiar nodos
<xsl:sort> para ordenar conjuntos de nodos
(select attribute especifica qué se debe ordenar)
Ejemplo: Ordenar los elementos "animal" por el numero de "legs"
en (animals.xml)
XML Input file:
<?xml version="1.0"?>
<animals>
<animal name="dog" class="mammal" legs="4"/>
<animal name="shark" class="fish" legs="0"/>
<animal name="chicken" class="bird" legs="2"/>
</animals>
XML Output file:
<?xml version="1.0"?>
<animals>
<animal name="shark" class="fish" legs="0"/>
<animal name="chicken" class="bird" legs="2"/>
<animal name="dog" class="mammal" legs="4"/>
</animals>
XSL Style Sheet:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:template match="text()">
</xsl:template>
<xsl:template match="animals">
<animals>
<xsl:apply-templates>
<xsl:sort data-type="number" select="@legs"/>
</xsl:apply-templates>
</animals>
</xsl:template>
<xsl:template match="animal">
<xsl:copy>
<xsl:apply-templates select="* | @*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="* | @*">
<xsl:copy>
<xsl:apply-templates select="* | @*"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Problema: Calcular el promedio de cada estudiante y el promedio del
grupo
XML Input file (students.xml):
XSL Style Sheet :
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:template match="course">
<xsl:apply-templates select="student"/>
total average="<xsl:value-of select="(sum(//hw1) +
sum(//hw2) +
sum(//final) +
sum(//project))
div (4*count(//student))"/>"
</xsl:template>
<xsl:template match="student">
<xsl:variable name="ave">
<xsl:value-of select="(hw1 + hw2 + project + final) div 4"/>
</xsl:variable>
Student name="<xsl:value-of select="name"/>"
average="<xsl:value-of select="$ave"/>"
</xsl:template>
</xsl:stylesheet>
Output file (grades.txt):
Student name="John Smith"
average="66.25"
Student name="George Lucas"
average="77.5"
Student name="Elizabeth Roberts"
average="73.75"
total average="72.5"
Problema: Desplegar el nombre de los estudiantes cuyos promedios
sean mayores que 70
XML Input file (students.xml):
XSL Style Sheet:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:template match="course">
<xsl:apply-templates select="student"/>
</xsl:template>
<xsl:template match="student">
<xsl:variable name="ave">
<xsl:value-of select="(hw1 + hw2 + project + final) div 4"/>
</xsl:variable>
<xsl:if test="$ave > 70">
Student name="<xsl:value-of select="name"/>"
average="<xsl:value-of select="$ave"/>"
</xsl:if>
</xsl:template>
</xsl:stylesheet>
Output file (grades70.txt):
Student name="George Lucas"
average="77.5"
Student name="Elizabeth Roberts"
average="73.75"
XML es el tipo por default
<xsl:output method="xml"/>
HTML 4.0
<xsl:output method="html"/>
Text
<xsl:output method="text"/>
Inserta espacios en blanco y sangrías
<xsl:output indent="yes"/>
Produce el elemento DOCTYPE
<xsl:output doctype-system="students.dtd"/>
*produces: <!DOCTYPE course SYSTEM "students.dtd">
Se derivó de las propuestas previas:
* XML-QL
* YATL
* Lorel
* Quilt
Se basa en XPath y en los XML Schema datatypes
Ejemplo:
let $i := 42 (: This is also a comment. :) |
<x>(: This is not a comment. :)</x> |
Comments
(: Esto es un comentario :) |
Prolog
declare function foo($param as xs:integer) as xs:string external; declare variable $var as xs:decimal external; |
Constructors
<add> |
<add>{ 1 + 1 = 2 }</add> |
|
|
document { |
<foo bar="2">baz<x xmlns='urn:x'>Ordinary XML can be |
declare function first( element $f) return element { let $firstChild := $f/*[1] return element{ xf:name($firstChild) } { xf:data($firstChild/@*[1]) } } |
first(<employee id="998359"> <status value="retired"/> <name>Alan Greene</name> </employee>) --> <status>retired</status> |
Built-in Functions (lista completa)
De propósito general
count(("a", 2, "c")) |
3 |
Numéricas
min((2, 1, 3, -100)) | -100 |
round(9 div 2) | 5 |
round-half-to-even(9 div 2) | 4 |
Booleanas
if (expr < 0) |
Caracteres
string-length("abcde") | 5 |
substring("abcde", 3) | cde |
substring("abcde", 2, 3) | bcd |
concat("ab", "cd", "", "e") | abcde |
string-join(("ab","cd","","e"), "") | abcde |
string-join(("ab","cd","","e"), "x") | abxcdxxe |
contains("abcde", "e") | true |
replace("abcde", "a.*d", "x") | xe |
replace("abcde", "([ab][cd])+", "x") | axde |
normalize-space(" a b cd e ") | a b cd e |
FLWOR (for, let, where,order, return)
let $dept := document("depts.xml") let $emp := document("employees.xml") for $e in $emp//employee $d in $dept//department where $e/dept eq $d/name return <employee name="{data($e/name)}" dept="{data($d/dept)}"/> |
--> <employee name="Albert Jones" dept="accounting"/> <employee name="Gloria French" dept="accounting"/> <employee name="Clark Hill" dept="security"/> |
for $i in doc("orders.xml")//Customer ( let $name := concat($i/@FirstName,$i/@LastName) |
Joins
for $i in doc("one.xml")//fish, |
Más ejemplos
document("recipes.xml")//recipe[title="Ricotta Pie"]//ingredient[@amount] |
for $d in document("depts.xml")//deptno let $e := document("emps.xml")//employee[deptno = $d] |
Para el empleo de XQuery sobre documentos XML se puede emplear Saxon
<?xml version="1.0"?> <addresses version="1.0"> <address id="1"> <fullname>Andreas Laux</fullname> <born day='1' month='12' year='1978'/> <town>Leipzig</town> <country>Germany</country> </address> </addresses> |
<?xml version="1.0"?> <xupdate:modifications version="1.0" xmlns:xupdate="http://www.xmldb.org/xupdate"> <xupdate:insert-after select="/addresses/address[1]" > <xupdate:element name="address"> <xupdate:attribute name="id">2</xupdate:attribute> <fullname>Lars Martin</fullname> <born day='2' month='12' year='1974'/> <town>Leizig</town> <country>Germany</country> </xupdate:element> </xupdate:insert-after> </xupdate:modifications> |
<?xml version="1.0"?> <addresses version="1.0"> <address id="1"> <fullname>Andreas Laux</fullname> <born day='1' month='12' year='1978'/> <town>Leipzig</town> <country>Germany</country> </address> <address id="2"> <fullname>Lars Martin</fullname> <born day='2' month='12' year='1974'/> <town>Leizig</town> <country>Germany</country> </address> </addresses> |
Insert ej. xupdate:insert-before inserta un nodo
como el hermano predecesor del nodo seleccionado
Estos elementos deben contener alguno de los siguientes elementos:
<xupdate:element name="address"> <town>San Francisco</town> </xupdate:element> |
<address> <town>San Francisco</town> </address> |
<xupdate:element name="address"> <xupdate:attribute name="id">2</xupdate:attribute> </xupdate:element> |
<address id="2"/> |
<xupdate:processing-instruction name="cocoon-process"> type="xsp" </xupdate:processing-instruction> |
<?cocoon-process type="xsp"?> |
<xupdate:comment> This element is automatically generated. </xupdate:comment> |
<!--This element is automatically generated. --> |
Append Se emplea para agregar un nodo como hijo de otro nodo Debe contener algunos de los siguientes elementos:
<xupdate:append select="/addresses" child="last()"> <xupdate:element name="address"> <town>San Francisco</town> </xupdate:element> </xupdate:append> |
<addresses> <address> <town>Los Angeles</town> </address> <address> <town>San Francisco</town> </address> </addresses> |
<xupdate:update select="/addresses/address[2]/town"> New York </xupdate:update> |
<addresses> <address> <town>Los Angeles</town> </address> <address> <town>New York</town> </address> </addresses> |
<xupdate:remove select="/addresses/address[1]"/> |
<addresses> <address> <town>New York</town> </address> </addresses> |
<xupdate:rename select="/addresses/address/town"> city </xupdate:rename> |
<addresses> <address> <city>New York</city> </address> </addresses> |
XML Enabled Databases (Bases de datos habilitadas para XML): son aquellas que desglosan la información de un documento XML en su correspondiente esquema relacional o de objetos
Product |
Developer |
License |
DB Type |
---|---|---|---|
Access 2002 |
Microsoft |
Commercial |
Relational |
Cache |
InterSystems Corp. |
Commercial |
Multi-valued |
DB2 |
IBM |
Commercial |
Relational |
eXtremeDB |
McObject |
Commercial |
Navigational |
FileMaker |
FileMaker |
Commercial |
FileMaker |
FoxPro |
Microsoft |
Commercial |
Relational |
Informix |
IBM |
Commercial |
Relational |
Matisse |
Matisse Software |
Commercial |
Object-oriented |
Objectivity/DB |
Objectivity |
Commercial |
Object-oriented |
OpenInsight |
Revelation Software |
Commercial |
Multi-valued |
Oracle 8i, 9i |
Oracle |
Commercial |
Relational |
SQL Server 2000 |
Microsoft |
Commercial |
Relational |
Sybase ASE 12.5 |
Sybase |
Commercial |
Relational |
Versant enJin |
Versant Corp. |
Commercial |
Object-oriented |
En un inicio, las bases de datos habilitadas para XML convertían la información a un esquema relacional y los queries se hacían en SQL, hoy día es posible no solo recuperar los resultados formateados en XML, sino interrogar a ese esquema relacional usando XPath o XQuery.
Ejemplo en: DB2, Oracle y MySQL
XML Native Databases (Bases de datos nativas de XML): son aquellas que respetan la estructura del documento, se pueden hacer consultas sobre dicha estructura y es posible recuperar el documento tal como fue insertado originalmente.
Product |
Developer |
License |
DB Type |
---|---|---|---|
4Suite, 4Suite Server |
FourThought |
Open Source |
Object-oriented |
Birdstep RDM XML |
Birdstep |
Commercial |
Object-oriented |
Centor Interaction Server |
Centor Software Corp. |
Commercial |
Proprietary |
Cerisent XQE |
Cerisent |
Commercial |
Proprietary(?) |
Coherity XML Database |
Coherity |
Commercial |
Proprietary |
DBDOM |
K. Ari Krupnikov |
Open Source |
Relational |
dbXML |
dbXML Group |
Commercial |
Proprietary |
DOM-Safe |
Ellipsis |
Commercial |
Proprietary |
eXist |
Wolfgang Meier |
Open Source |
Relational |
eXtc |
M/Gateway Developments Ltd. |
Commercial |
Multi-valued |
eXtensible Information Server (XIS) |
eXcelon Corp. |
Commercial |
Object-oriented (ObjectStore). Relational and other data through Data Junction |
GoXML DB |
XML Global |
Commercial |
Proprietary (Text-based) |
Infonyte DB |
Infonyte |
Commercial |
Proprietary (Model-based) |
Ipedo XML Database |
Ipedo |
Commercial |
Proprietary |
Lore |
Stanford University |
Research |
Semi-structured |
Lucid XML Data Manager |
Ludic'i.t. |
Commercial |
Proprietary |
MindSuite XDB |
Wired Minds |
Commercial |
Object-oriented |
Natix |
data ex machina |
Commercial |
File system(?) |
Neocore XML Management System |
NeoCore |
Commercial |
Proprietary |
ozone |
ozone-db.org |
Open Source |
Object-oriented |
Sekaiju / Yggdrasill |
Media Fusion |
Commercial |
Proprietary |
SQL/XML-IMDB |
QuiLogic |
Commercial |
Proprietary (native XML and relational) |
Tamino |
Software AG |
Commercial |
Proprietary. Relational through ODBC. |
TeraText DBS |
TeraText Solutions |
Commercial |
Proprietary |
TEXTML Server |
IXIA, Inc. |
Commercial |
Proprietary (Text-based) |
TigerLogic XDMS |
Raining Data |
Commercial |
Pick |
TOTAL XML |
Cincom |
Commercial |
Object-relational? |
Virtuoso |
OpenLink Software |
Commercial |
Proprietary. Relational through ODBC |
XDBM |
Matthew Parry, Paul Sokolovsky |
Open Source |
Proprietary (Model-based) |
XDB |
ZVON.org |
Open Source |
Relational (PostgreSQL only?) |
X-Hive/DB |
X-Hive Corporation |
Commercial |
Object-oriented (Objectivity/DB). Relational through JDBC |
Xindice |
Apache Software Foundation |
Open Source |
Proprietary (Model-based) |
Xyleme Zone Server |
Xyleme SA |
Commercial |
Proprietary |
Afortunadamente el grupo XMLDB ha propuesto un API que todos los proveedores deben implementar Al igual que con otras aplicaciones el API simplemente define un conjunto de interfaces que cada proveedor implementa:
org.xmldb.api InterfacesDatabaseManager org.xmldb.api.base InterfacesCollection Configurable Database Resource ResourceIterator ResourceSet Service Classes ErrorCodes Exceptions XMLDBException org.xmldb.api.modules InterfacesBinaryResource CollectionManagementService TransactionService XMLResource XPathQueryService XUpdateQueryService |
Una colección es un conjunto de documentos (una base de datos)
Un recurso es un documento dentro de la colección
Un servicio es una facilidad que permite hacer hacer acciones que van desde búsquedas hasta inserciones, etc.
Agregando un documento |
1:import org.xmldb.api.*; 2:import org.xmldb.api.base.*; 3:import org.xmldb.api.modules.*; 4: 5:import java.io.*; 6:import org.exist.util.XMLUtil; 7: 8:public class AddExample { 9: 10: public static void main(String args[]) throws Exception { 11: 12: String collection = args[0], file = args[1]; 13: 14: if(collection.startsWith("/db")) 15: // remove /db if specified 16: collection = collection.substring(3); 17: 18: // initialize driver 19: String driver = "org.exist.xmldb.DatabaseImpl"; 20: Class cl = Class.forName(driver); 21: Database database = (Database)cl.newInstance(); 22: database.setProperty("create-database", "true"); 23: DatabaseManager.registerDatabase(database); 24: 25: // try to get collection 26: Collection col = 27: DatabaseManager.getCollection("xmldb:exist://localhost:8080/exist/xmlrpc/db" + collection,"carlos","proal"); 28: if(col == null) { 29: // collection does not exist: get root collection and create it 30: Collection root = DatabaseManager.getCollection("xmldb:exist://localhost:8080/exist/xmlrpc/db","admin","lolo");); 31: CollectionManagementService mgtService = 32: (CollectionManagementService) 33: root.getService("CollectionManagementService", "1.0"); 34: col = mgtService.createCollection(collection); 35: } 36: // create new XMLResource; an id will be assigned to the new resource 37: XMLResource document = (XMLResource)col.createResource(null, "XMLResource"); 38: 39: File f = new File(file); 40: if(!f.canRead()) 41: System.err.println("can't read file " + file); 42: document.setContent(f); 43: System.out.print("storing document " + document.getId() + "..."); 44: col.storeResource(document); 45: System.out.println("ok."); 46: } 47:} 48: 49: |
Recuperación de un documento |
1:import org.xmldb.api.base.*; 2:import org.xmldb.api.modules.*; 3:import org.xmldb.api.*; 4: 5:public class RetrieveExample { 6: public static void main(String args[]) throws Exception { 7: String driver = "org.exist.xmldb.DatabaseImpl"; 8: Class cl = Class.forName(driver); 9: Database database = (Database)cl.newInstance(); 10: DatabaseManager.registerDatabase(database); 11: database.setProperty("create-database", "true"); 12: 13: Collection col = 14: DatabaseManager.getCollection("xmldb:exist://localhost:8080/exist/xmlrpc/db/test","carlos","proal"); 15: col.setProperty("pretty", "true"); 16: col.setProperty("encoding", "ISO-8859-1"); 17: XMLResource res = (XMLResource)col.getResource(args[0]); 18: 19: if(res == null) { 20: System.err.println("could not retrieve document " 21: + args[0] + "!"); 22: return; 23: } 24: System.out.println((String)res.getContent()); 25: } 26:} 27: 28: 29: 30: |
Ejecutando una consulta |
1:import org.xmldb.api.base.*; 2:import org.xmldb.api.modules.*; 3:import org.xmldb.api.*; 4: 5:public class QueryExample { 6: public static void main(String args[]) throws Exception { 7: String driver = "org.exist.xmldb.DatabaseImpl"; 8: Class cl = Class.forName(driver); 9: Database database = (Database)cl.newInstance(); 10: database.setProperty("create-database", "true"); 11: DatabaseManager.registerDatabase(database); 12: 13: Collection col = 14: DatabaseManager.getCollection("xmldb:exist://localhost:8080/exist/xmlrpc/db/test","carlos","proal"); 15: XPathQueryService service = 16: (XPathQueryService) col.getService("XPathQueryService", "1.0"); 17: service.setProperty("pretty", "true"); 18: service.setProperty("encoding", "ISO-8859-1"); 19: 20: ResourceSet result = service.query(args[0]); 21: ResourceIterator i = result.getIterator(); 22: while(i.hasMoreResources()) { 23: Resource r = i.nextResource(); 24: System.out.println((String)r.getContent()); 25: } 26: } 27:} 28: 29: 30: |
Ejecutando una actualización |
1:mport org.xmldb.api.base.*; 2:import org.xmldb.api.modules.*; 3:import org.xmldb.api.*; 4:import java.io.*; 5: 6:public class UpdateExample { 7: public static void main(String args[]) throws Exception { 8: String driver = "org.exist.xmldb.DatabaseImpl"; 9: Class cl = Class.forName(driver); 10: Database database = (Database)cl.newInstance(); 11: database.setProperty("create-database", "true"); 12: DatabaseManager.registerDatabase(database); 13: 14: Collection col = 15: DatabaseManager.getCollection("xmldb:exist://localhost:8080/exist/xmlrpc/db/test","carlos","proal"); 16: XUpdateQueryService service = 17: (XUpdateQueryService) col.getService("XUpdateQueryService", "1.0"); 18: service.setProperty("pretty", "true"); 19: service.setProperty("encoding", "ISO-8859-1"); 20: 21: File file=new File(args[0]); 22: char[] xmlmodification=new char[file.length()]; 23: new FileReader(file).read(xmlmodification,0,new Long(file.length()).intValue()); 24: String xupdate=new String(xmlmodification); 25: long updated = service.update(xupdate); 26: System.out.println(updated+" updated resources"); 27: 28: } 29:} |
*Los resultados estarán expresados en XML
Básicamente la utilización radica en los siguientes pasos: