8. Datos Semiestructurados · 8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados:...

38
8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados: Lo que sea entre estructurado y no estructurado Variables pobremente tipadas (x=1 es válido y x=”hola” también es válido) Un registro no necesariamente tiene que tener todos sus atributos definidos. Mientras por ejemplo en una base de datos relacional un campo debe establecerse como NULL cuando no se tiene, en un ambiente de datos semiestructurados basta con omitir dicho atributo. Un atributo de un registro puede ser otro registro No existe necesariamente una diferencia entre un identificador de un campo y el valor mismo de este. Ejemplos: documentos SGML y XML A pesar de poder representarse de dintintas maneras, actualmente la mejor manera de hacerlo es a través del lenguaje XML, por eso en las secciones siguientes se aborda la definición, representación, almacenamiento e interrogación de estos documentos. 8.2 XML: Extensible Markup Language. 8.2.1 Definición Qué es XML ? Extensible Markup Language XML 1.0 1998 Es un subconjunto de SGML (Standard Generalized Markup Language) XML es un lenguaje de marcado basado en texto Estándar para el intercambio de datos en la web Conjunto de reglas para el diseño semántico de tags Lenguaje de Meta-markup para definir otros lenguajes La especificación oficial la da el W3C http://www.w3.org/TR/REC-xml HTML y XML HTML es una aplicación de SGML XML es un subconjunto de SGML XHTML es una aplicación de XML XML Archivo Ejemplo <?xml version="1.0"?> <dining-room> <manufacturer>The Wood Shop</manufacturer> <table type="round" wood="maple"> <price>$199.99</price> </table> <chair wood="maple"> <quantity>6</quantity> <price>$39.99</price> </chair> </dining-room> XML describe Estructura y Semántica, NO Formato Ejemplo HTML <DL> <DT>Mambo <DD>by Enrique Garcia </DL> <UL> <LI>Producer: Enrique Garcia

Transcript of 8. Datos Semiestructurados · 8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados:...

Page 1: 8. Datos Semiestructurados · 8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados: Lo que sea entre estructurado y no estructurado Variables pobremente tipadas (x=1

8. Datos Semiestructurados

8.1 Introducción

Datos semiestructurados:

Lo que sea entre estructurado y no estructuradoVariables pobremente tipadas (x=1 es válido y x=”hola” también es válido)Un registro no necesariamente tiene que tener todos sus atributos definidos. Mientras por ejemplo en una base de datos relacional un campo debeestablecerse como NULL cuando no se tiene, en un ambiente de datos semiestructurados basta con omitir dicho atributo.Un atributo de un registro puede ser otro registroNo existe necesariamente una diferencia entre un identificador de un campo y el valor mismo de este.Ejemplos: documentos SGML y XML

A pesar de poder representarse de dintintas maneras, actualmente la mejor manera de hacerlo es a través del lenguaje XML, por eso en las secciones siguientesse aborda la definición, representación, almacenamiento e interrogación de estos documentos.

8.2 XML: Extensible Markup Language.

8.2.1 Definición

Qué es XML ?

Extensible Markup Language XML 1.0 1998Es un subconjunto de SGML (Standard Generalized Markup Language)XML es un lenguaje de marcado basado en textoEstándar para el intercambio de datos en la webConjunto de reglas para el diseño semántico de tagsLenguaje de Meta-markup para definir otros lenguajesLa especificación oficial la da el W3Chttp://www.w3.org/TR/REC-xml

HTML y XML

HTML es una aplicación de SGMLXML es un subconjunto de SGMLXHTML es una aplicación de XML

XML Archivo Ejemplo

<?xml version="1.0"?> <dining-room> <manufacturer>The Wood Shop</manufacturer> <table type="round" wood="maple"> <price>$199.99</price> </table> <chair wood="maple"> <quantity>6</quantity> <price>$39.99</price> </chair> </dining-room>

XML describe Estructura y Semántica, NO Formato

Ejemplo HTML

<DL> <DT>Mambo <DD>by Enrique Garcia </DL> <UL> <LI>Producer: Enrique Garcia

Page 2: 8. Datos Semiestructurados · 8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados: Lo que sea entre estructurado y no estructurado Variables pobremente tipadas (x=1

<LI>Publisher: Sony Music Entertainment <LI>Length: 3:46 <LI>Written: 1991 <LI>Artist: Azucar Moreno </UL>

Ejemplo XML

<SONG> <TITLE>Mambo</TITLE> <COMPOSER>Enrique Garcia</COMPOSER> <PRODUCER>Enrique Garcia</PRODUCER> <PUBLISHER>Sony Music Entertainment</PUBLISHER> <LENGTH>3:46</LENGTH> <YEAR>1991</YEAR> <ARTIST>Azucar Moreno</ARTIST> </SONG>

Por qué es conveniente usar XML?

Facilita el Intercambio de Datos

Crecimiento de formatos propietariosProgramas de Conversión (Aplicaciones, versiones, etc)Tantos los datos como las marcas son almacenados en modo textoEvita almacenar datos simples en archivos enormes

Hacer lenguajes a la medida de las necesidades

Banking Industry Technology Secretariat (BITS)Financial Exchange (IFX)Schools Interoperability Framework (SIF)Common Business Library (CBL)Electronic Business XML Initiative (ebXML)Text Encoding Initiative (TEI)

Datos auto-descriptivos

<?xml version="1.0" encoding="UTF-8"?> <DOCUMENT> <GREETING>Hello from XML</GREETING> <MESSAGE>Welcome to Programing XML in Java</MESSAGE> </DOCUMENT>

Datos organizados (semi-estructurados) e integrados

<?xml version="1.0"?> <SCHOOL> <CLASS type="seminar"> <CLASS_TITLE>XML In The Real World</CLASS_TITLE> <CLASS_NUMBER>6.031</CLASS_NUMBER> <SUBJECT>XML</SUBJECT> <START_DATE>6/1/2002</START_DATE> <STUDENTS> <STUDENT status="attending"> <FIRST_NAME>Edward</FIRST_NAME> <LAST_NAME>Samson</LAST_NAME> </STUDENT> <STUDENT status="withdrawn"> <FIRST_NAME>Ernestine</FIRST_NAME> <LAST_NAME>Johnson</LAST_NAME> </STUDENT> </STUDENTS> </CLASS> </SCHOOL>

8.2.2 Tipos de Documentos XML

Documentos XML Bien-Formados (Well-Formed)

Son aquellos documentos XML que:

Siguen las reglas de sintáxis establecidad por el W3C en:XML 1.0 (www.w3.org/TR/REC-xml)Contienen uno o más elementosPoseen un elemento Root que contiene dentro de él los demás elementosCada elemento debe anidarse dentro de otro correctamente (uno dentro de otro)

Page 3: 8. Datos Semiestructurados · 8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados: Lo que sea entre estructurado y no estructurado Variables pobremente tipadas (x=1

Documentos XML Válidos (Valid)

Asociación con un DTD (Document Type Definition)Cumplir con la especificación del DTD

<?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/css" href="first.css"?> <!DOCTYPE DOCUMENT [ <!ELEMENT DOCUMENT (GREETING, MESSAGE)> <!ELEMENT GREETING (#PCDATA)> <!ELEMENT MESSAGE (#PCDATA)> ]>

<DOCUMENT> <GREETING>Hello from XML</GREETING> <MESSAGE>Welcome to Programing XML in Java</MESSAGE> </DOCUMENT>

Tecnologías Relacionadas

Hypertext Markup Language

HTML es el formato de salida más común para XMLNavegadores: Internet Explorer 5.0, Netscape 6.0Una manera diferente de diseñar sitios web

Cascading Style Sheets (CSS)

Definir propiedades de formatoFont SizeFont familyFont weightParagraph indentationParagraph alignment

Múltiples hojas de estilo pueden ser aplicadas a un mismo documentoMúltiples estilos pueden aplicarse a un sólo elemento

URLs and URIs

Uniform Resource Locator (URL)http://www.google.comActualmente ya no son utilizadosUniform Resource Name (URN)urn:issn:1011.-911.3http://purl.oclc.org/OCLC/PURL/FAQUniform Resource Identifier (URI)

The Unicode Character Set

American Standard Code for Information Interchange (ASCII) 0-255 'A' - 65XML brinda soporte para el Unicode de 2 bytes. 0-65,535http://www.unicode.orgXML acepta documentos escritos en:

ASCIIUTF-11.Compressed version of Unicode (utiliza 11.bits para representar)<?xml version="1.0" encoding="UTF-8"?>

XML define un referencia para codificar caracteres Unicode&#xA9; &lt; &#x03C0;

Universal Character System (UCS ISO 10646)4 bytes por symbolCodificación UCS-2 y UCS-4

Page 4: 8. Datos Semiestructurados · 8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados: Lo que sea entre estructurado y no estructurado Variables pobremente tipadas (x=1

8.2.3 Utilización de documentos XML

Cómo se utiliza ?

El documento XML es parseado (analizado sintáctica y gramaticalmente)Los datos son manipuladosAPIs disponibles en Java, C, C++, Perl, etc

Para hacer este "parsing" se utilizan 2 técnicas

SAX (Simple API for XML)DOM (Document Object Model)

Simple API for XML - SAX

Sistema basado en eventos (event-based) para el análisis de los datosMétodos como startDocument(), endElement()Conjunto de Errores y Warningshttp://www.megginson.com/SAXMuchos analizadores están basadon en el SAX API

Document Object Model - DOM

Manipulación de datos XMLBrinda una representación del documento a manera de árbolLee todo el documento XML en memoriahttp://www.w3.org/DOM

Sun's Java API for XML Parsing - JAXP

Mezcla de SAX y DOM APIsAlgunos métodos adicionaleshttp://java.sun.com/xml

Java y XML: La pareja ideal

Java es código portable, XML son datos portablesAplicaciones completamente portables

Java Virtual Machine (JVM)Capas de datos basadas en estándares

Java provee el más robusto conjunto de:APIs - JAXPParsers - XPProcessors - SaxonPublishing Frameworks - CocoonTools for XML - XML Pro

El ciclo original de un documento XML

Page 5: 8. Datos Semiestructurados · 8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados: Lo que sea entre estructurado y no estructurado Variables pobremente tipadas (x=1

Editores de XML

Sirven para crear documentos XML

Editores de Texto - vi, emacs, notepadEditores de XML

Adobe FrameMaker, www.adobe.comXML Pro, www.vervet.comXML Writer, xmlwriter.netXML Notepad, msdn.microsoft.com/xml/notepad/intro.aspXMetal from SoftQuad, xmetal.comXML Spy, www.xmlspy.com

Editores de XML (XML Spy)

XML Parsers

Leen el documento XML1.Verifican si el documento XML está bien-formado (well formed)2.Verifican si el documento es válido3.

expat, parser escrito en C por James Clark (www.jclark.com)XML for Java (XML4J), IBM Alphaworks(www.alphawors.ibm.com/tech/xml4j)Lark, escrito en Java (www.textuality.com/Lark/)Apache Xerces (www.apache.org)XP por James Clark (www.jclark.com)

Page 6: 8. Datos Semiestructurados · 8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados: Lo que sea entre estructurado y no estructurado Variables pobremente tipadas (x=1

Oracle XML Parser (technet.oracle.com/tech/xml)Sun Microsystems Project X (java.sun.com/products/xml)

XML Validators

Unicamente verifican si un documento es válido

XML.com's Validador basado en Lark (xml.com)Language Technology Group en la Universidad of Edinburgo validador basado en el RXP Parserwww.ltg.ed.ac.uk/~richard/xml-check.htmlScholarly Technology Group en la Universidad Brownwww.stg.brown.edu/service/xmlvalid/

XML Browsers

Despliegan los datos al usuario

Internet Explorer 5Despliega directamente Documentos XMLManipula XML en lenguajes de scripting (JScript, VBScript)Liga XML con registros de bases de datos a través de ActiveX Data Object (ADO)XML integrado como parte de las aplicaciones del Office 2000 y superiores

Netscape Navigator 6Despliega directamente Documentos XMLManipula XML en lenguajes de scripting (Javascript 1.5)Soporta el XML-based User Interface Language (XUL). XUL permite configurar los controles del navegador

JumboDespliega XMLUsa CML para dibujar moléculas

Recursos disponibles en el web acerca de XML

XML en W3C (http://www.w3.org/xml/)XML.com (http://www.xml.com/XML.org Registry (http://www.xml.org/)XML Cover Pages (http://xml.coverpages.org/)Java and XML (http://java.sun.com/xml/)

Page 7: 8. Datos Semiestructurados · 8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados: Lo que sea entre estructurado y no estructurado Variables pobremente tipadas (x=1

Aplicaciones XML

Lenguajes basados en XML

Chemical Markup Language (CML)Mathematical Markup Language (MathML)Channel Definition Format (CDF)Synchronized Multimedia Integration Language (SMIL)XHTMLScalable Vector Graphics (SVG)MusicMLVoxML

8.3 Documentos XML

8.3.1 Creando Documentos XML

Documentos XML

HTML, posee cerca de 100 elementosXML, cada quien define sus propios elementosHTML Browsers intentan arreglar código HTML inválidoXML Processors no hacen ninguna averiguación acerca de la estructura del documentoUn documento bien-formado es lo mínimo que debe cumplir un documento para ser XMLMejor aún si es un documento XML válido (DTD o XML Schema)World Wide Web Consortium (http://www.w3.org/)

Qué es un documento XML bien-formado ?

Es un documento de texto está bien-formado si:

tomado como un todo, coinciden las etiquetas del documento1.Cumple con las reglas de formación mencionadas en la especificación:http://www.w3.org/TR/REC-xml

2.

Cada una de las entidades analizadas o parseadas que se encuentran referenciadas directa o indirectamente en el documento están bien formadas3.

Componentes de un documento XML

document ::= prolog element Misc*

Prolog:<?xml version="1.0"?>

Comentarios -> <!-- This is a Comment -->Instrucciones de Procesamiento:<?xml-stylesheet href="JavaXML.html.xsl" type="text/xsl"?><?xml-stylesheet href="greeting.css" type="text/css"?>

Element:Elemento raíz (root), que a su vez contiene más elementosExactamente una sola raíz

Misc:ComentariosInstrucciones de ProcesamientoEspacios

Tags y Elements

Un elemento XML consiste de un tag de inicio y un tag de terminación<document> ... </document>

Reglas de nombres de TagDeben empezar con una letra <document>, un guión bajo <_record> o bien 2 puntos (aunque no se recomienda)Los siguientes caracteres pueden ser: letra, número, guión, guión bajo, punto, dos puntos, pero NO espacios es blancoLos procesadores de XML y en consecuencia los documentos son "case sensitive"

Page 8: 8. Datos Semiestructurados · 8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados: Lo que sea entre estructurado y no estructurado Variables pobremente tipadas (x=1

Los siguientes tags son diferentes: <document>, <DOCUMENT>, <Document>Elementos Vacíos tienen únicamente un tag:HTML : <img>, <li>, <hr>XHTML : <img/>, <li/>, <hr/>

Attributes

Parejas nombre-valor: {STATUS, "Good Credit"}Información adicional del elemento, especificada en los tags de inicio<CUSTOMER STATUS="Good credit">

Los nombres sigues las mismas reglas que los los nombres de tagsLos valores de los atributos son cadenas encerradas en comillas " "

Elements vs Attributes

Demasiados atributos hacen que los documentos sean más difíciles de leer

Ejemplo 1: <CUSTOMER LAST_NAME="Smith" FIRST_NAME="Sam" DATE="October 15, 2001" PURCHASE="Tomatoes" PRICE="$1.25" NUMBER="8" />

Ejemplo 2:

<CUSTOMER> <NAME> <LAST_NAME>Smith</LAST_NAME> <FIRST_NAME>Sam</FIRST_NAME> </NAME> <DATE>October 15, 2001</DATE> <ORDERS> <ITEM> <PRODUCT>Tomatoes</PRODUCT> <NUMBER>8</NUMBER> <PRICE>$1.25</PRICE> </ITEM> </ORDERS> </CUSTOMER>

No se puede representar una estructura sólo con atributosAtributos son buenos para información sencilla<BOOK ID="B1">

Construyendo la estructura de un Documento XML Bien-Formado

Debe comenzar con una declaración<?xml version="1.0" standalone="yes"?>

Debe incluir uno o más elementos

<?xml version="1.0" encoding="UTF-8"?><DOCUMENT><GREETING>Hello from XML</GREETING><MESSAGE>Welcome to Programing XML in Java</MESSAGE></DOCUMENT>

Incluir ambos tags (inicio y terminación) para aquellos elementos que no están vacíos

<GREETING>Hello from XML</GREETING>

Cerrar los tags vacíos con /><SUBJECT name="XML"/>

Se debe establecer un elemento raíz que debe contener a todos los demás elementos<DOCUMENT> ..... </DOCUMENT>

Page 9: 8. Datos Semiestructurados · 8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados: Lo que sea entre estructurado y no estructurado Variables pobremente tipadas (x=1

Mezclar los elementos de manera correcta:

<?xml version="1.0" encoding="UTF-8"?><DOCUMENT> <GREETING>Hello from XML</MESSAGE> <--- error end tag <MESSAGE> Welcome to Programing XML in Java </GREETING> <--- error end tag</DOCUMENT>

Utilizar nombres únicos para los atributos:

<PERSON LAST_NAME="Smith" LAST_NAME="Punin"> <--- error mismo nombre

Utilizar las 5 referencias ya existentes de entidades:

&amp; & &lt; < &gt; > &apos; ` &quot; "

<TOUR CAPTION="The S&amp;O Railway"/>

Encerrar los valores de atributos con comillas:

<IMG SRC="image.jpg"/>

CDATA Sections

Son secciones que contienen datos que permanecen intactos al ser analizados por un Procesador XMLComienzan con: <![CDATA[Terminan con: ]]>

<?xml version="1.0"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/tr/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Using The if Statement In JavaScript</title> </head> <body> <script language="javascript"> <![CDATA[ var budget budget = 234.77 if (budget < 0){ document.writeln("Uh oh.")} ]]> </script> <center> <h1>Using The if Statement In JavaScript</h1> </center> </body></html>

8.3.2 Creación de DTDs (Document Type Definitions)

Document Type Definition:Especifica la estructura y sintáxis de un documento XML

<!ELEMENT DOCUMENT (CUSTOMER)*> <!ELEMENT CUSTOMER (NAME,DATE,ORDERS)> <!ELEMENT NAME (LAST_NAME,FIRST_NAME)> <!ELEMENT LAST_NAME (#PCDATA)> <!ELEMENT FIRST_NAME (#PCDATA)> <!ELEMENT DATE (#PCDATA)> <!ELEMENT ORDERS (ITEM)*> <!ELEMENT ITEM (PRODUCT,NUMBER,PRICE)>

Page 10: 8. Datos Semiestructurados · 8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados: Lo que sea entre estructurado y no estructurado Variables pobremente tipadas (x=1

<!ELEMENT PRODUCT (#PCDATA)> <!ELEMENT NUMBER (#PCDATA)> <!ELEMENT PRICE (#PCDATA)>

Mini Ejemplo de un documento válido y un DTD

<?xml version="1.0"?><!DOCTYPE BOOK [ <!ELEMENT BOOK (P*)> <!ELEMENT P (#PCDATA)>]>

<BOOK> <P>chapter 1 - Intro</P> <P>chapter 2 - Conclusion</P> <P>Index</P></BOOK>

Sintáxis de DTDs

Document Type Declaration (declaración del DTD)

<!DOCTYPE rootname [DTD]>

<!DOCTYPE rootname SYSTEM URL>

<!DOCTYPE rootname SYSTEM URL [DTD]>

<!DOCTYPE rootname PUBLIC identifier URL>

<!DOCTYPE rootname PUBLIC identifier URL [DTD]>

Ejemplo de DTD

<?xml version="1.0"?><!DOCTYPE BOOK [ <!ELEMENT p (#PCDATA)> <!ELEMENT BOOK (OPENER,SUBTITLE?,INTRODUCTION?,(SECTION | PART)+)> <!ELEMENT OPENER (TITLE_TEXT)*> <!ELEMENT TITLE_TEXT (#PCDATA)> <!ELEMENT SUBTITLE (#PCDATA)> <!ELEMENT INTRODUCTION (HEADER, p+)+> <!ELEMENT PART (HEADER, CHAPTER+)> <!ELEMENT SECTION (HEADER, p+)> <!ELEMENT HEADER (#PCDATA)> <!ELEMENT CHAPTER (CHAPTER_NUMBER, CHAPTER_TEXT)> <!ELEMENT CHAPTER_NUMBER (#PCDATA)> <!ELEMENT CHAPTER_TEXT (p)+>]><BOOK> <OPENER> <TITLE_TEXT>All About Me</TITLE_TEXT> </OPENER> <PART> <HEADER>Welcome To My Book</HEADER> <CHAPTER> <CHAPTER_NUMBER>CHAPTER 1</CHAPTER_NUMBER> <CHAPTER_TEXT> <p>Glad you want to hear about me.</p> <p>There's so much to say!</p> <p>Where should we start?</p> <p>How about more about me?</p> </CHAPTER_TEXT> </CHAPTER> </PART></BOOK>

External DTDs (Privates)

Nombre del archivo:

<?xml version="1.0" standalone="no"?><!DOCTYPE BOOK SYSTEM "book.dtd"><BOOK>......</BOOK>

URL:

<?xml version="1.0" standalone="no"?><!DOCTYPE BOOK SYSTEM "http://www.library.org/book.dtd"><BOOK>......</BOOK>

External DTDs (Publics)

<!DOCTYPE name PUBLIC "FPI" "URL">

Page 11: 8. Datos Semiestructurados · 8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados: Lo que sea entre estructurado y no estructurado Variables pobremente tipadas (x=1

Formal Public Identifier (FPI)

Primer campo: no standard, + standard DTDSegundo campo: nombre de grupo o persona responsable del DTDTercer campo: tipo de documento y número de versiónCuarto campo: lenguaje (2 letras)Campos separados por //

<!DOCTYPE BOOK PUBLIC "-//Joseph Smith//General Book Version 5.3//EN" "http://www.library.org/book.dtd">

XHTML Document

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><head> <title>Virtual Library</title></head><body> <p>Moved to <a href="http://vlib.org/">vlib.org</a>.</p></body></html>

Definición de Elementos

<!ELEMENT name content_model>

Ejemplos :<!ELEMENT direction (left, right, top?)>

<!ELEMENT CHAPTER (INTRODUCTION, (P | QUOTE | NOTE)*, DIV*)>

<!ELEMENT HR EMPTY>

<!ELEMENT p (#PCDATA | I)* >

<!ELEMENT %title; %content; >

<!ELEMENT DOCUMENT ANY>

Content_model

ANYCualquier tipo de contenido - Elementos o PCDATA<!ELEMENT DOCUMENT ANY>

Listas de elementos hijosNombres de los elementos en paréntesis<!ELEMENT direction (left, right, top?)>

#PCDATA (Parsed Character Data)Texto sin marcas<!ELEMENT First_Name (#PCDATA)>

Múltiples Hijos

a+ - Una o más ocurrencias de a<!ELEMENT BOOK (CHAPTER)+>

a* - Cero o más ocurrencias de a<!ELEMENT List (Object)*>

a? - a o nada<!ELEMENT Table (plate)?>

a, b - a seguido de b<!ELEMENT SUM (op1, op2)>

a | b - a o b pero no no ambos<!ELEMENT POINT (COORDINATES | POLAR)>

(expression) - expresiones que pueden ser tomadas como una sola<!ELEMENT CHAPTER (INTRODUCTION, (P | QUOTE | NOTE)*, DIV*)>

Sequences

<!ELEMENT Name (Last_Name, First_Name)

<Name> <Last_Name>Punin</Last_Name> <First_Name>John</First_Name> </Name>

Choices

<!ELEMENT ITEM (PRODUCT, NUMBER, (PRICE | CHARGEACCT | SAMPLE))>

<ITEM>

Page 12: 8. Datos Semiestructurados · 8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados: Lo que sea entre estructurado y no estructurado Variables pobremente tipadas (x=1

<PRODUCT>Tomatoes</PRODUCT> <NUMBER>8</NUMBER> <PRICE>$1.25</PRICE> </ITEM> <ITEM> <PRODUCT>Oranges</PRODUCT> <NUMBER>24</NUMBER> <SAMPLE>$4.98</SAMPLE> </ITEM>

Mixed Content

Ejemplo 1:

<!ELEMENT PRODUCT (#PCDATA | PRODUCT_ID)*>

<PRODUCT>Tomatoes</PRODUCT>

<PRODUCT> <PRODUCT_ID>12411.95411.02121</PRODUCT_ID></PRODUCT>

Ejemplo 2:

<!ELEMENT p (#PCDATA | b)*><!ELEMENT b (#PCDATA)>

<p>This is <b>bold</b> text</p>

Elementos Vacíos & Comentarios en DTDs

Elementos Vacíos:

<!ELEMENT CREDIT_WARNING EMPTY>

<CREDIT_WARNING></CREDIT_WARNING> or <CREDIT_WARNING/>

Comentarios DTD:

<!-- DOCUMENT is the root element --> <!ELEMENT DOCUMENT (CUSTOMER)*>

Attributes

Parejas Nombre/ValorAgregan información adicional a los tags de inicio

<CUSTOMER LAST_NAME="Smith" FIRST_NAME="Sam" DATE="February 6, 2001" PURCHASE="Tomatoes" PRICE="$1.25" NUMBER="8" />

Declarando atributos en DTDs

<!ATTLIST element_name attribute_name type default_value attribute_name type default_value . . . attribute_name type default_value>

element_name - nombre del elementoattribute_name - nombre del atributotype - tipo del atributo (ver siguiente sección)default_value - valor por default

<!ELEMENT greeting (#PCDATA)><!ATTLIST greeting language CDATA "English">

<greeting language="Spanish"> Hola!</greeting>

Tipos de Atributos

CDATA - Simple Character Data - Texto que no lleva marcas

<!ELEMENT Rectangle EMPTY> <!ATTLIST Rectangle length CDATA "0px"

Page 13: 8. Datos Semiestructurados · 8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados: Lo que sea entre estructurado y no estructurado Variables pobremente tipadas (x=1

width CDATA "0px">

<Rectangle width="11.px" length="40px"/>

Valores por default para CDATA

#REQUIRED

No hay un default, pero el atributo del documento debe indicar algun valor necesariamente

<!ELEMENT img EMPTY> <!ATTLIST img alt CDATA #REQUIRED src CDATA #REQUIRED> <img src="xmlj.jpg" alt="XMLJ Image"/>

#IMPLIED

No hay un default, y el atributo del documento no necesariamente tiene que utilizarse

<!ELEMENT img EMPTY> <!ATTLIST img alt CDATA #REQUIRED src CDATA #REQUIRED width CDATA #IMPLIED height CDATA #IMPLIED>

<img src="xmlj.jpg" alt="XMLJ Image" width="300"/>

#FIXED VALUE

Se fija el valor del atributo al valor "VALUE".

<!ELEMENT ADDRESS (#PCDATA)> <!ATTLIST ADDRESS country CDATA #FIXED "USA">

<ADDRESS country="USA">123 15th St. Troy NY 12111.</ADDRESS>

Enumerated - Listas de valores (se debe usar alguno de ellos)

<!ELEMENT TITLE (#PCDATA)> <!ATTLIST TITLE ALIGN (LEFT | CENTER | RIGHT) "LEFT"> <TITLE>Programming XML in Java</TITLE>

<TITLE ALIGN="CENTER">Programming XML in Java</TITLE>

NMTOKEN - Una palabra que no puede contener letras, números, '.', '-', '_', o ':'. No puede tener espacios

<!ELEMENT student_name (#PCDATA)> <!ATTLIST student_name student_no NMTOKEN #REQUIRED> <student_name student_no="9216735">Jo Smith</student_name>

NMTOKENS - Palabras que pueden tokenizarse por espacios

<!ATTLIST performances dates NMTOKENS #REQUIRED>

<performances dates="27-02-1977 04-11-1911. 24-12-2002"> Kat and the Kings</performances>

IDIdentificador único del atributoNo debe aparecer más de un sola vez en el documento XMLEl primer caracter deber una letra o '_', o ':'Lo demas caracteres no pueden ser espacios.

<!ELEMENT student_name (#PCDATA)> <!ATTLIST student_name student_id ID #REQUIRED>

Page 14: 8. Datos Semiestructurados · 8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados: Lo que sea entre estructurado y no estructurado Variables pobremente tipadas (x=1

<student_name student_id="S9216735">Jo Smith</student_name>

IDREF - Referencia hacia el ID de otro elemento.

<?xml version="1.0" standalone="yes"?><!DOCTYPE lab_group [ <!ELEMENT lab_group (student_name)*> <!ELEMENT student_name (#PCDATA)> <!ATTLIST student_name student_id ID #REQUIRED tutor IDREF #IMPLIED> ]>

<lab_group> <student_name student_id="S11.0411.5">Alex Foo</student_name> <student_name student_id="S9011133">Sarah Bar</student_name> <student_name student_id="S9216735" tutor="S11.0411.5">Jo Smith</student_name></lab_group>

Entidades (Entities)

La manera en XML de identificar un elemento de datosPuede ser texto o datos binarios.General Entity

Se usa en el contenido de un documentoLas referencias empiezan con '&' y terminan con ';'

Parameter EntitySe usa en un DTDLas referencias empiezan con '%' y terminan con ';'

Internal Entity - Definida en un documento XMLExternal Entity - Definina en una fuente externa: archivo, URI.

Internal General Entities

<!ENTITY name definition>

Ejemplo 1:

<!ELEMENT DATE (#PCDATA)> <!ENTITY TODAY "February 7, 2001">

<DATE>&TODAY;</DATE>

Ejemplo 2:

<!ENTITY NAME "John Punin"> <!ENTITY CNAME "&NAME; Palacios">

External General Entities

<!ENTITY name SYSTEM URI><!ENTITY name PUBLIC FPI URI>

Ejemplo:

<!ELEMENT DATE (#PCDATA)> <!ENTITY TODAY SYSTEM "date.xml">

<DATE>&TODAY;</DATE>

Predefined General Entity References

&amp; - La letra &&apos; - La letra '&gt; - La letra >&lt; - La letra <&quot; - La letra "

<!ELEMENT EMAIL (#PCDATA)><!ENTITY at_new "&#64;">

<EMAIL>carlos.proal&at_new;gmail.com</EMAIL>

Page 15: 8. Datos Semiestructurados · 8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados: Lo que sea entre estructurado y no estructurado Variables pobremente tipadas (x=1

Parameter Entities

Internal<!ENTITY % name definition>

External<!ENTITY % name SYSTEM URI><!ENTITY % name PUBLIC FPI URI>

Ejemplo:

<!ELEMENT CUSTOMER (NAME, DATE, ORDERS)> <!ELEMENT BUYER (NAME, DATE, ORDERS)> <!ELEMENT DISCOUNTER (NAME, DATE, ORDERS)>

<!ENTITY % record "(NAME, DATE, ORDERS)"> <!ELEMENT CUSTOMER %record;> <!ELEMENT BUYER %record;> <!ELEMENT DISCOUNTER %record;>

8.4 XPath

8.4.1 XML Path

Expresiones para identificar partes particulares de un documento XML

Especifica un nodo o un conjunto de nodos

Una ruta de localización (location path) consiste en uno o más pasos de localización

Rutas absolutas comienzan con /

Rutas relativas NO comienzan con /

Los pasos pueden ser:Eje (axis)Nodo a ser interrogado (node test)0 o más predicados (predicates)

child::student[position() = 2]child (axis)student (node test)position() = 2 (predicate)

8.4.2 XPath axis

ancestor

ancestor-or-self

attribute

child

descendant

descendant-or-self

following

following-sibling

namespace

parent

preceding

preceding-sibling

self

8.4.3 XPath Node tests

comment()

node()

Page 16: 8. Datos Semiestructurados · 8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados: Lo que sea entre estructurado y no estructurado Variables pobremente tipadas (x=1

processing-instruction()

text()

8.4.4 XPath Predicates

Node Sets

last() - Returns the number of nodes in a node setposition() - Returns the position of the context node count(node-set) - Returns the number of nodeslocal-name(node-set) - Returns the local name of the first nodenamespace-uri(node-set) - Returns the URI of the namespace of the first nodename(node-set) - Returns the full, qualified name of the first node

Booleans != - Is not equal to< - Is less than (use < in XML documents)<= - Is less than or equal to= - Is equal to> - Is greater than>= - Is greater than or equal toand - And operatoror - Or operatortrue() - returns truefalse() - returns false

Example:

<xsl:template match="student[position() > 2]"> ... </xsl:template>

Numbers + - Addition- - Substraction* - Multiplicationdiv - Divisionmod - Modulusceiling() - Smallest integerfloor() - Largest integerround() - Nearest integersum() - Sum of numbers

Strings starts-with(string string1, string string2) - Booleancontains(string string1, string string2) - Booleansubstring(string string1, number offset, number length) - Stringsubstring-before(string string1, string string2) - Stringsubstring-after(string string1, string string2) - Stringstring-length(string string1) - Numbernormalize-space(string string1) - Stringtranslate(string string1, string string2,string string3) - Stringconcat(string string1, string string2,...) - String

Result tree fragments

8.4.5 Ejemplo de XPath

child::studentattribute::iddescendant::nameancestor::hw1self::teacher/descendant::student/child::namechild::student[attribute::id="js"]child::student[child::name]

8.4.6 Sintáxis abreviada de XPath

Page 17: 8. Datos Semiestructurados · 8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados: Lo que sea entre estructurado y no estructurado Variables pobremente tipadas (x=1

Expression

self::node()parent::node()child::childnameattribute::childname/descendant-or-self::node()/

Abbreviation

.

..childname@childname//

XPath Abbreviated Syntax Examples

student*text()@idstudent[2]*/student/course/student[2]/name//student../@idstudent[name]student[name="John Punin"]student[id="js"]student[hw1 or hw2]

8.5 Extensible Style Language Transformations (XSLT)

8.5.1 Qué es XSL?

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

8.5.2 Operaciones en árbol dentro de XSL

Page 18: 8. Datos Semiestructurados · 8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados: Lo que sea entre estructurado y no estructurado Variables pobremente tipadas (x=1

8.5.3 Usando XSLT Style Sheets

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">

Page 19: 8. Datos Semiestructurados · 8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados: Lo que sea entre estructurado y no estructurado Variables pobremente tipadas (x=1

<P> <xsl:value-of select="name"/> </P> </xsl:template> </xsl:stylesheet>

Realizando la transformación

En el servidor - Debe existir un programa, ej Java Servlet, que utiliza la hoja de estilo para transformarlo automáticamente enviarlo alcliente

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>

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.

Con un programa independiente - Programas o aplicaciones que realizan todas las acciones con algun objetivo en particular

8.5.4 Procesadores de XSLT

Oracle XML parser for Javahttp://technet.oracle.com/tech/xml/parser_java2/

Saxonhttp://users.iclway.co.uk/mhkay/saxon/index.html

XThttp://www.jclark.com/xml/xt.html

Sablotronhttp://www.gingerall.com/charlie-bin/get/webGA/act/sablotron.act

Microsoft XML Parserhttp://msdn.microsoft.com/downloads/webtechnology/xml/msxml.asp

Xalan Javahttp://xml.apache.org/xalan-j/index.html

Procesando hojas de estilo

A través de un browser

Un documento xml puede hacer referencia a una hoja de estilo para que un navegador o visualizador pueda formatear dicho documento ydesplegarlo 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 conextensión xml.

Utilizando el procesador Xalan

XML document (students.xml)XSLT style sheet (students.xsl)Xalan jar file (xalan.jar) de Apache

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:

Page 20: 8. Datos Semiestructurados · 8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados: Lo que sea entre estructurado y no estructurado Variables pobremente tipadas (x=1

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:

Output File (students.html)

<HTML> <HEAD> <TITLE>Name of students</TITLE> </HEAD> <BODY> <P>John Smith</P> <P>George Lucas</P> <P>Elizabeth Roberts</P> </BODY> </HTML>

8.5.5 Creando XSLT Style Sheets

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

XSLT Style Sheets are well formed XML Documents

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>

Page 21: 8. Datos Semiestructurados · 8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados: Lo que sea entre estructurado y no estructurado Variables pobremente tipadas (x=1

La hoja de estilo más simple, sin hacer nada.

<?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>

El elemento xsl:apply-templates

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>

El elemento xsl:value-of

Obtener el valor de los nodos y poder escribirlo en archivo de salida

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>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:

Page 22: 8. Datos Semiestructurados · 8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados: Lo que sea entre estructurado y no estructurado Variables pobremente tipadas (x=1

<HTML> <HEAD> <TITLE>Name of students</TITLE> </HEAD> <BODY> <P>John Smith</P> <P>George Lucas</P> <P>Elizabeth Roberts</P> </BODY> </HTML>

Manejando selecciones múltiples con xsl:for-each

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>

Especificando patrones para el atributo "match"

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:

Page 23: 8. Datos Semiestructurados · 8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados: Lo que sea entre estructurado y no estructurado Variables pobremente tipadas (x=1

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">

Page 24: 8. Datos Semiestructurados · 8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados: Lo que sea entre estructurado y no estructurado Variables pobremente tipadas (x=1

<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">

Page 25: 8. Datos Semiestructurados · 8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados: Lo que sea entre estructurado y no estructurado Variables pobremente tipadas (x=1

<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>

8.5.6 Reglas por default de XSLT

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()"/>

Page 26: 8. Datos Semiestructurados · 8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados: Lo que sea entre estructurado y no estructurado Variables pobremente tipadas (x=1

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

8.5.7 Creando "templates" para atributos

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>

8.5.8.Creando nuevos Elementos

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"/>

Page 27: 8. Datos Semiestructurados · 8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados: Lo que sea entre estructurado y no estructurado Variables pobremente tipadas (x=1

<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>

8.5.9 Creando nuevos Atributos

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>

Page 28: 8. Datos Semiestructurados · 8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados: Lo que sea entre estructurado y no estructurado Variables pobremente tipadas (x=1

<xsl:attribute name="legs"> <xsl:value-of select="@legs"/> </xsl:attribute> </xsl:element> </xsl:template> </xsl:stylesheet>

8.5.10 Copiando y ordenando nodos

<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>

8.5.11 Usando "xsl:variable" y "text output" type

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"/>

Page 29: 8. Datos Semiestructurados · 8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados: Lo que sea entre estructurado y no estructurado Variables pobremente tipadas (x=1

<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"

8.5.12 Usando "xsl:if"

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"

8.5.13 Controlando el tipo de salida

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

Page 30: 8. Datos Semiestructurados · 8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados: Lo que sea entre estructurado y no estructurado Variables pobremente tipadas (x=1

<xsl:output doctype-system="students.dtd"/>

*produces: <!DOCTYPE course SYSTEM "students.dtd">

8.6 XQuery

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. :)

return <x>(: This is not a comment. :)</x>

<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> {{ 1 + 1 = { 1+1 }}}</add>

<add>{ 1 + 1 = 2 }</add>

<employee empid="{$id}"><name>{$name}</name>{$job}<deptno>{$deptno}</deptno><salary>{$SGMLspecialist+100000}</salary></employee>

<employee empid="12345"><name>John Doe</name><job>XML specialist</job><deptno>187</deptno><salary>125000</salary></employee>

document { element foo { attribute bar { 1 + 1 } text { "baz" } <x xmlns='urn:x'>Ordinary XML can be intermixed with the alternate syntax</x> }}

<foo bar="2">baz<x xmlns='urn:x'>Ordinary XML can be intermixed with the alternate syntax</x></foo>

declare function first( element $f) first(<employee id="998359"> <status value="retired"/>

Page 31: 8. Datos Semiestructurados · 8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados: Lo que sea entre estructurado y no estructurado Variables pobremente tipadas (x=1

return element

{ let $firstChild := $f/*[1] return element{ xf:name($firstChild) } { xf:data($firstChild/@*[1]) }}

<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)) -100round(9 div 2) 5round-half-to-even(9 div 2) 4

Booleanas

if (expr < 0) then "negative"else if (expr > 0) then "positive"else "zero"

Caracteres

string-length("abcde") 5substring("abcde", 3) cdesubstring("abcde", 2, 3) bcdconcat("ab", "cd", "", "e") abcdestring-join(("ab","cd","","e"), "") abcdestring-join(("ab","cd","","e"), "x") abxcdxxecontains("abcde", "e") truereplace("abcde", "a.*d", "x") xereplace("abcde", "([ab][cd])+", "x") axdenormalize-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//departmentwhere $e/dept eq $d/namereturn <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)where $i/@ZipCode = 91126order by $i/@LastNamereturn<Customer Name="{$name}">{ $i//Order }</Customer>

Joins

for $i in doc("one.xml")//fish,

$j in doc("two.xml")//fish

where $i/red = $j/blue

return <fishes> { $i, $j } </fishes>

Page 32: 8. Datos Semiestructurados · 8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados: Lo que sea entre estructurado y no estructurado Variables pobremente tipadas (x=1

Más ejemplos

document("recipes.xml")//recipe[title="Ricotta Pie"]//ingredient[@amount]

for $d in document("depts.xml")//deptnolet $e := document("emps.xml")//employee[deptno = $d]

where count($e) >= 10

order by avg($e/salary) descending

return <big-dept>

{ $d, <headcount>{count($e)}</headcount>, <avgsal>{avg($e/salary)}</avgsal>

} </big-dept>

Para el empleo de XQuery sobre documentos XML se puede emplear Saxon

8.7 XUpdate

Namespace El namespace correspondiente a Xupdate es descrito en el URI http://www.xmldb.org/xupdate. Selects Toda actualización, al igual que encualquier base de datos, requiere una selección de datos sobre los cuales aplicar dichos cambios; XUpdate continua con el estándar de utilizar XPath paradicho propósito. Modification Toda modificación debe estar contenida en un elemento xupdate:modifications el cual debe contener un atributo indicando laversion de XUpdate necesaria (ej 1.0). A su vez, el elemento modifications debe contener alguno de los siguientes elementos, dependiendo del tipo de cambioa realizar

xupdate:insert-beforexupdate:insert-afterxupdate:appendxupdate:updatexupdate:removexupdate:renamexupdate:variablexupdate:value-ofxupdate:if

<?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

<xupdate:element name="address"> <town>San Francisco</town> </xupdate:element>

<address> <town>San Francisco</town> </address>

xupdate:attribute

<xupdate:element name="address"> <xupdate:attribute name="id">2</xupdate:attribute> </xupdate:element>

<address id="2"/>

Page 33: 8. Datos Semiestructurados · 8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados: Lo que sea entre estructurado y no estructurado Variables pobremente tipadas (x=1

xupdate:textxupdate:processing-instruction<xupdate:processing-instruction name="cocoon-process"> type="xsp"</xupdate:processing-instruction>

<?cocoon-process type="xsp"?>

xupdate:comment

<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:elementxupdate:attributexupdate:textxupdate:processing-instructionxupdate:comment

<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>

Updates Se emplea para actualizar el contenido de algun nodo

<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>

Remove

<xupdate:remove select="/addresses/address[1]"/>

<addresses> <address> <town>New York</town> </address></addresses>

Rename

<xupdate:rename select="/addresses/address/town"> city </xupdate:rename>

<addresses> <address> <city>New York</city> </address> </addresses>

8.8 XML Databases

8.8.1 Antecedentes

El analizar un documento XML no es trivial, aunque se puede hacer con SAX o DOMXPath y XSLT (Xalan) permiten hacer búsquedas en un documento de una manera sencilla a través de dicho lenguaje de consultaCuando hablamos de realizae un búsqueda en una colección (conjunto de) documentos las cosas cambian, la complejidad aumenta y se deben buscaralternativas

Page 34: 8. Datos Semiestructurados · 8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados: Lo que sea entre estructurado y no estructurado Variables pobremente tipadas (x=1

8.8.2 Definición

Hablar de documentos XML es hablar de 2 categorías

Centrados en los datos (data-centric): usados para el transporte de datos ya que probablemente estaremos hablando de datos estructurados organizadosen XMLCentrados en el documento (document-centric): tienen una estructura irregular y sobre todo, esa estructura es importante

Para cada caso la manera de realizar una consulta es diferente: Para los documentos centrados en los datos, podemos pensar en datos estructurados que pueden extraerse del documento e indexarse con alguna base de datosconvencional Por otro lado para los datos centrados en el documento el reto no es tan trivial ya que se pretende hacer consultas pero no solo sobre elcontenido, sino también sobre la estructura del documento. De modo que una base de datos XML es aquella que define un modelo lógico de un documentoXML y almacena y recupera documentos de acuerdo a ese modelo.

8.8.3 Tipos de Bases de Datos XML

XML Enabled Databases (Bases de datos habilitadas para XML): son aquellas que desglosan la información de un documento XML en sucorrespondiente esquema relacional o de objetos

Product Developer License DB TypeAccess 2002 Microsoft Commercial RelationalCache InterSystems Corp. Commercial Multi-valuedDB2 IBM Commercial RelationaleXtremeDB McObject Commercial NavigationalFileMaker FileMaker Commercial FileMakerFoxPro Microsoft Commercial RelationalInformix IBM Commercial RelationalMatisse Matisse Software Commercial Object-orientedObjectivity/DB Objectivity Commercial Object-orientedOpenInsight Revelation Software Commercial Multi-valuedOracle 8i, 9i Oracle Commercial RelationalSQL Server 2000 Microsoft Commercial RelationalSybase ASE 12.5 Sybase Commercial RelationalVersant 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íaes 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 dichaestructura y es posible recuperar el documento tal como fue insertado originalmente.

Page 35: 8. Datos Semiestructurados · 8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados: Lo que sea entre estructurado y no estructurado Variables pobremente tipadas (x=1

Product Developer License DB Type

4Suite, 4Suite Server FourThought Open Source Object-oriented

Birdstep RDM XML Birdstep Commercial Object-orientedCentor Interaction Server Centor Software Corp. Commercial ProprietaryCerisent XQE Cerisent Commercial Proprietary(?)Coherity XML Database Coherity Commercial Proprietary

DBDOM K. Ari Krupnikov Open Source

Relational

dbXML dbXML Group Commercial ProprietaryDOM-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 JunctionGoXML DB XML Global Commercial Proprietary (Text-based)Infonyte DB Infonyte Commercial Proprietary (Model-based)Ipedo XML Database Ipedo Commercial ProprietaryLore Stanford University Research Semi-structuredLucid XML Data Manager Ludic'i.t. Commercial ProprietaryMindSuite XDB Wired Minds Commercial Object-orientedNatix 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 ProprietarySQL/XML-IMDB QuiLogic Commercial Proprietary (native XML and relational)Tamino Software AG Commercial Proprietary. Relational through ODBC.TeraText DBS TeraText Solutions Commercial ProprietaryTEXTML Server IXIA, Inc. Commercial Proprietary (Text-based)TigerLogic XDMS Raining Data Commercial PickTOTAL 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

Page 36: 8. Datos Semiestructurados · 8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados: Lo que sea entre estructurado y no estructurado Variables pobremente tipadas (x=1

8.8.4 Programando con una XML Database

Afortunadamente el grupo XMLDB ha propuesto un API que todos los proveedores deben implementar Al igual que con otras aplicaciones elAPI simplemente define un conjunto de interfaces que cada proveedor implementa:

org.xmldb.api

InterfacesDatabaseManager

org.xmldb.api.base

Interfaces Collection Configurable Database Resource ResourceIterator ResourceSet Service Classes ErrorCodes Exceptions XMLDBException

org.xmldb.api.modules

Interfaces BinaryResource CollectionManagementService TransactionService XMLResource XPathQueryService XUpdateQueryService

Es importante recordar:

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.

Imports: import org.xmldb.api.base.*;import org.xmldb.api.modules.*;import org.xmldb.api.*; El driver puede ser: "org.exist.xmldb.DatabaseImpl" "org.apache.xindice.client.xmldb.DatabaseImpl"El url puede ser xmldb:exist://localhost:8080/exist/xmlrpc/db/thesis xmldb:xindice://localhost:4080/db/thesis

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

Page 37: 8. Datos Semiestructurados · 8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados: Lo que sea entre estructurado y no estructurado Variables pobremente tipadas (x=1

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: }

Page 38: 8. Datos Semiestructurados · 8. Datos Semiestructurados 8.1 Introducción Datos semiestructurados: Lo que sea entre estructurado y no estructurado Variables pobremente tipadas (x=1

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

8.8.5 Utilizando una XML Database

Básicamente la utilización radica en los siguientes pasos:

Escoger una XMLDatabase (exist y xindice son los más recomendables)Instalarla, configurarla y de preferencia crear usuarios y permisosCrear un DTD que deberán seguir todos los documentos de la colecciónFormular los posibles queries en XPath que deseamos obtener de la colecciónCrear las aplicaciones que ejecuten las distintas acciones en la XMLDBDiseñar las XSL que den formato a los resultados de las búsquedasIntegrar todas las partes