XML Distribucin y Componentes Tema 1 Procesamiento XML
XML, Distribución y Componentes Tema 1 – Procesamiento XML en. NET http: //paginaspersonales. deusto. es/dipina/Master. ISW/ Dr. Diego Lz. de Ipiña Gz. de Artaza http: //paginaspersonales. deusto. es/dipina (Personal) http: //www. morelab. deusto. es (Research Group) http: //www. smartlab. deusto. es (Research Lab) http: //www. ctme. deusto. es (Cátedra de Telefónica Móviles) http: //www. tecnologico. deusto. es (Tecnológico-Fundación Deusto) Fundación Deusto - Tecnológico Deusto
Temario n Procesamiento XML en. NET (21 y 22 Febrero) ¨ ¨ ¨ n Aplicaciones distribuidas (23 Febrero, 5 Marzo) ¨ ¨ ¨ n Estándar. NET [XML. NET] Soporte XML [XML-SAX, XML-DOM, Validación] XSL [XPath, XSLT, Scripts, Objetos de extensión] XML/SOAP. NET Remoting Mensajería Componentes. NET (6 y 7 Marzo) ¨ ¨ ¨ ¨ Metadatos y Reflexion Componentes. NET y Enterprise Services Complementos Interoperabilidad COM y P/Invoke COM+ y MTS MSMQ (colas de mensajes) Microsoft Communication Foundation (Indigo) 2
Contenidos Parte XML n XML ¨ DTD ¨ Schema n XML Parsing ¨ SAX API ¨ DOM API n XSLT ¨ XSLT Scripts ¨ XSLT Object Extensions 3
¿Qué es XML? n n n e. Xtensible Mark-up Language. Es un metalenguaje que permite diseñar otros lenguajes (WML, Math. ML, XHTML, . . ). Cualquiera puede desarrollar su propio lenguaje de etiquetas adecuado al tipo de aplicación que más le convenga. En realidad hay muchas tecnologías basadas en XML (XPath, XLink, XPointer, XSL, . . . ). XML 1. 0 Specification http: //www. w 3. org/TR/REC-xml 4
HTML y XML n n SGML (Standard Generalized Markup Language) HTML es una aplicación de SGML XML es subconjunto más fácil de usar de SGML XHTML es una aplicación de XML 5
XML describe estructura y semántica <? xml version=” 1. 0”> <!DOCTYPE comedor SYSTEM “comedor. dtd”> <comedor> <fabricante>Ipiña Altzariak</fabricante> <mesa tipo="redonda" madera="arce"> <precio>€ 400</precio> </mesa> <silla madera="arce"> <cantidad>2</cantidad> <calidad>excelente</calidad> <cojin incluido="sí"> <color>azul</color> </cojin> <precio>€ 200</precio> </silla> </comedor> 6
HTML describe formato <html> <head><title>Comedor</title></head> <body> <h 1>Comedor</h 1> <p>Fabricante: Ipiña Altzariak</p> <ul> <li><b>Mesa redonda de madera de arce</b></li> <li><b>Dos sillas de madera de arce</b>, de excelente calidad, con un cojín azul cada una. </li> <li><b>3 sillas de madera de roble</b>. </li> </ul> </body> </html> 7
Ventajas XML n n Una de las mayores utilidades de XML es poder etiquetar los datos con su significado (self-describing data). Permite la estructuración de la información. Ello lleva el tratamiento automático de la información a límites insospechados. XML es la base de la nueva generación de aplicaciones web intercambio de datos 8
Usos XML n Sitios web ¨ Permite n separar contenido y presentación Comunicación <-> intercambio datos ¨ Servicios n web Como configuración de programas ¨ Deployment descriptos en servidores J 2 EE ¨ Ant make system 9
Componentes documento XML n Los documentos XML constan de: ¨ Instrucciones de procesamiento (processing instructions – PI) ¨ Declaraciones de tipo de documento ¨ Comentarios ¨ Elementos ¨ Referencias a entidades ¨ Secciones CDATA 10
Instrucciones de procesamiento n n Las PI son instrucciones para el procesador del documento XML. Siempre hay al menos una PI, que pertenece al prólogo del documento: <? xml version="1. 0"? > <saludo> Hola, mundo! </saludo> n Algunos navegadores interpretan la siguiente instrucción de procesamiento para indicar que el documento debería ser procesado mediante una hoja de estilo Guitars. xsl antes de ser visualizado: <? xml-stylesheet type="text/xsl" href="Guitars. xsl"? > 11
Comentarios en XML n n Los comentarios no se procesan. Tienen la siguiente sintaxis: <!-- Esto es un comentario --> 12
Elementos y atributos en XML n n Los elementos son los que aportan estructura semántica al documento. Se delimitan por etiquetas de apertura, cierre y etiquetas sin elementos interiores (etiquetas vacías). Las etiquetas de apertura y las vacías suelen venir acompañadas de atributos, que parametrizan el elemento. El valor de los atributos siempre se encierra entre comillas, dobles o simples. <saludo tipo="coloquial">Hola</saludo> 13
Elementos vs. Atributos n n Demasiados atributos hacen que los documentos XML se puedan leer difícilmente. No se puede indicar estructura de documento mediante atributos <CUSTOMER LAST_NAME="Smith" FIRST_NAME="Sam" DATE="October 15, 2001" PURCHASE="Tomatoes" PRICE=“€ 1. 25" NUMBER="8" /> 14
Elementos vs. Atributos (cont) <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> 15
Referencias a entidades n Las referencias a entidades sirven para insertar un determinado contenido definido previamente. <!ENTITY Empresa “Universidad de Deusto”> <pie>Creado por &Empresa; </pie> 16
Códigos de escape n Existen 5 referencias a entidades predefinidas: el carácter & ¨ < el carácter < ¨ > el carácter > ¨ ' el carácter ' ¨ " el caracter " ¨ & n Se incluyen los caracteres del juego ISO 10646. ¨ ¨ &#x 2 F 31; 17
Secciones CDATA n n Las secciones CDATA (character data) contienen texto que no debe ser procesado. Se tratan como una secuencia de caracteres sin estructura. <![CDATA[<saludo>Hola, mundo!</saludo>]]> 18
Gramáticas en XML n La gramática que restringe los elementos válidos dentro de un nuevo derivado de XML puede expresarse en forma de: ¨ DTD (Document Type Definitions) o ¨ Esquemas XML 19
Document Type Definitions (DTDs) n n Especifican la estructura y sintaxis de un documento XML Labgroups. dtd <!ELEMENT lab_group (student_name)*> <!ELEMENT student_name (#PCDATA)> <!ATTLIST student_name dni ID #REQUIRED tutor IDREF #IMPLIED> 20
Document Type Definitions (cont) <? xml version="1. 0"? > <!DOCTYPE mensaje SYSTEM “labgroups. dtd"> <lab_group> <student_name dni=“ 44670523"> Josu Artaza </student_name> <student_name dni=“ 44543211"> Nuria Buruaga </student_name> <student_name dni=“ 23554521" tutor=“ 33456211"> Inga Dorsman </student_name> </lab_group> 21
XML Schemas n Los DTD no son muy potentes para definir gramáticas. n Otra forma de hacerlo es con Esquemas XML basados en el propio XML y que soporta más tipos de datos. 22
Ejemplo Schema n DTD : <!ELEMENT text (#PCDATA | emph | name)*> <!ATTLIST text timestamp NMTOKEN #REQUIRED> n XML Schema: <xsd: element name="text"> <xsd: complex. Type mixed="true"> <xsd: sequence> <xsd: element ref="emph"/> <xsd: element ref="name"/> </xsd: sequence> <xsd: attribute name="timestamp" type="xsd: date" use="required"/> </xsd: complex. Type> </xsd: element> 23
Ejemplo Schema (cont) n XML Document: <? xml version="1. 0"? > <text timestamp="08: 45: 00. 000">The deadline of <name>Distributed. NET assigment</name> is <emph>December 22 nd 2005</emph>. </text> 24
What is an XML Schema? n n n Extraído de: http: //www. w 3 schools. com/schema/default. asp The purpose of an XML Schema is to define the legal building blocks of an XML document, just like a DTD. An XML Schema: ¨ ¨ ¨ ¨ defines elements that can appear in a document defines attributes that can appear in a document defines which elements are child elements defines the order of child elements defines the number of child elements defines whether an element is empty or can include text defines data types for elements and attributes defines default and fixed values for elements and attributes 25
XML Schemas are the Successors of DTDs n We think that very soon XML Schemas will be used in most Web applications as a replacement for DTDs. Here are some reasons: ¨ XML Schemas are extensible to future additions ¨ XML Schemas are richer and more powerful than DTDs ¨ XML Schemas are written in XML ¨ XML Schemas support data types ¨ XML Schemas support namespaces 26
Ejemplo XML y DTD n Ejemplo XML: <? xml version="1. 0"? > <!DOCTYPE note SYSTEM "http: //www. w 3 schools. com/dtd/note. dtd"> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> n Ejemplo DTD: <!ELEMENT <!ELEMENT note (to, from, heading, body)> to (#PCDATA)> from (#PCDATA)> heading (#PCDATA)> body (#PCDATA)> 27
Ejemplo XML y Schema n Ejemplo XML: <? xml version="1. 0"? > <note xmlns="http: //www. w 3 schools. com" xmlns: xsi="http: //www. w 3. org/2001/XMLSchema-instance" xsi: schema. Location="http: //www. w 3 schools. com note. xsd"> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> n Ejemplo DTD: <? xml version="1. 0"? > <xs: schema xmlns: xs=http: //www. w 3. org/2001/XMLSchema target. Namespace=http: //www. w 3 schools. com xmlns=http: //www. w 3 schools. com element. Form. Default="qualified"> <xs: element name="note"> <xs: complex. Type> <xs: sequence> <xs: element name="to" type="xs: string"/> <xs: element name="from" type="xs: string"/> <xs: element name="heading" type="xs: string"/> <xs: element name="body" type="xs: string"/> </xs: sequence> </xs: complex. Type> </xs: element> </xs: schema> 28
Elementos Simples <xs: element name="xxx" type="yyy"/> n donde xxx es el nombre del elemento e yyy el tipo, siendo los más comunes: ¨ ¨ ¨ n xs: string xs: decimal xs: integer xs: boolean xs: date xs: time Ejemplos: <lastname>Refsnes</lastname> <age>36</age> <dateborn>1970 -03 -27</dateborn> 29
Atributos y Restricciones en Elementos n Ejemplo atributos: <lastname lang="EN">Smith</lastname> <xs: attribute name="lang" type="xs: string"/> n Ejemplo restricciones sobre un elemento: <xs: element name="letter"> <xs: simple. Type> <xs: restriction base="xs: string"> <xs: pattern value="[a-z]"/> </xs: restriction> </xs: simple. Type> </xs: element> 30
XML bien formado y/o XML válido n Hay dos tipos de documentos XML: ¨ Bien formados: son aquellos que cumplen las reglas sintácticas de XML ¨ Válidos: son aquellos que, además de ser bien formados, siguen las reglas de una gramática (definida en un DTD o XML Schema) 31
Reglas para que un documento esté bien formado n Para que un documento esté bien formado: ¨ Debe tener un prólogo ¨ Debe tener una etiqueta raíz ¨ Las etiquetas se hallan correctamente anidadas ¨ Se usan caracteres válidos y bien aplicados ¨ Los valores de los atributos vienen encerrados entre comillas ¨. . . 32
Reglas para que un documento sea válido n n Para que un documento sea válido debe declarar el DTD o XML Schema contra el cual debe validarse. Se hace mediante DOCTYPE, pudiendo ser los DTD públicos o de sistema. <!DOCTYPE saludo SYSTEM “saludo. dtd”> <!DOCTYPE saludo PUBLIC “-//Saludos//DTD Lenguaje de saludos//ES” “http: //www. deusto. es/dtds/saludo. dtd”> n También se puede insertar el DTD entero en ese punto, en lugar de referenciar al fichero. 33
Proceso de validación documento XML 34
XML Namespaces n n n El estándar XML también define los espacios de nombres (XML Namespaces). Permiten que un mismo documento XML tenga etiquetas de diferentes lenguajes (definidas en diferentes gramáticas DTD). Así es posible mezclar más información en los documentos, por ejemplo, añadir información semántica a un documento XHTML. 35
Ejemplo XML Namespaces <? xml version="1. 0"? > <!DOCTYPE mensaje SYSTEM "mensaje. dtd"> <mensaje> <remite> <dir: direccion xmlns: dir=“http: //www. deusto. es/direccion”> <dir: calle>Avda. Universidades</dir: calle> <dir: localidad cp=“ 40007”>Bilbao</dir: localidad> </dir: direccion> <nombre>Diego Ipiña</nombre> <email>dipina@eside. deusto. es</email> </remite> <!-- Resto del mensaje XML. . . --> </mensaje> 36
Lenguajes basados en XML n n n n n Chemical Markup Language (CML) Mathematical Markup Language (Math. ML) Channel Definition Format (CDF) Synchronized Multimedia Integration Language (SMIL) XHTML Scalable Vector Graphics (SVG) SOAP y WSDL Voice. ML Wireless Markup Language (WML) RSS (Rich Site Summary) 37
Herramientas de XML n Editores ¨ ¨ n http: //www. xmlcooktop. com/ gratis XML Spy, www. xmlspy. com XML parsers ¨ ¨ ¨ Lee un documento XML Verifica que XML está bien formado Verifican que XML es válido l l n expat, parser written in C by James Clark (www. jclark. com) Lark, written in Java (www. textuality. com/Lark/) Apache Jakarta Xerces (www. apache. org). NET FCL System. Xml XML Validators ¨ Verifican que XML es válido l XML. com's Validator based on Lark (xml. com) 38
¿Por qué usar XML? n n n Un documento XML puede ser fácilmente procesado y sus datos manipulados Existen APIs para procesar esos documentos en Java, C, C#, C++, Perl. . (y por supuesto Python) XML define datos portables al igual que Java define código portable 39
XML Parsing 40
XML Parsing (cont) n SAX Define interfaz dirigido por eventos (event-driven) para el procesamiento de un documento XML ¨ Definido por David Megginson y lista correo XML-DEV : http: //www. megginson. com/SAX ¨ n DOM Provee una representación de un documento XML en forma de un árbol ¨ Carga todo el documento XML en memoria ¨ http: //www. w 3. org/DOM ¨ 41
XML en. NET n El espacio de nombres System. Xml ofrece una variedad de clases para leer y escribir documentos XML: ¨ La clase Xml. Document implementa DOM ¨ Para un procesamiento orientado al stream se puede usar Xml. Text. Reader o Xml. Validating. Reader ¨ Xml. Text. Writer simplifica el proceso de creación de documentos XML. 42
System. XML n n n Este espacio de nombres comprende todas las clases necesarias para manejar documentos XML. Permite leer o parsear un documento, así como escribir un documento XML. Para ello necesitaremos conocer previamente la estructura de un documento XML. 43
System. XML n Este espacio de nombres provee soporte para los estándares de procesamiento XML: ¨ ¨ ¨ ¨ XML 1. 0 - http: //www. w 3. org/TR/1998/REC-xml-19980210 including DTD support. XML Namespaces - http: //www. w 3. org/TR/REC-xml-names/ - both stream level and DOM. XSD Schemas - http: //www. w 3. org/2001/XMLSchema XPath expressions - http: //www. w 3. org/TR/xpath XSLT transformations - http: //www. w 3. org/TR/xslt DOM Level 1 Core - http: //www. w 3. org/TR/REC-DOM-Level-1/ DOM Level 2 Core - http: //www. w 3. org/TR/DOM-Level-2/ 44
Un poco de XML n n n Lenguaje mundial de facto para intercambio de datos XML no tiene tanto éxito porque es un gran lenguaje, sino porque las herramientas disponibles para leer, escribir y manipular XML son muy comunes Casi todos los parseadores de XML implementan una de dos APIs: ¨ DOM: lee un documento en memoria y lo carga en un árbol ¨ SAX: API basada en eventos 45
Ejemplo DOM en. NET <? xml version=“ 1. 0”? > <Guitars> <Guitar Image=“My. SG. jpeg”> <Make>Gibson</Make> <Model>SG</Model> <Year>1977</Year> <Color>Tobacco Sunburst</Color> <Neck>Rosewood</Neck> </Guitar> <Guitar Image=“My. Strat. jpeg”> <Make>Fender</Make> <Model>Stratocaster</Model> <Year>1990</Year> <Color>Black</Color> <Neck>Maple</Neck> </Guitars> 46
Ejemplo DOM en. NET using System; using System. Xml; class My. App { static void Main () { Xml. Document doc = new Xml. Document (); doc. Load ("Guitars. xml"); Xml. Node. List nodes = doc. Get. Elements. By. Tag. Name ("Guitar"); foreach (Xml. Node node in nodes) { Console. Write. Line ("{0} {1}", node["Make"]. Inner. Text, node["Model"]. Inner. Text); } } } 47
Xml. Document n n n Interfaz programática para documentos XML que conforman con la especificación DOM Método Load(nombre-doc) procesa el documento y construye un árbol del mismo Una llamada exitosa es normalmente seguida de invocación a propiedad Document. Element ¨ Para saber si tiene hijos usar propiedad Has. Child. Nodes ¨ Propiedad Child. Nodes devuelve los hijos de un nodo l Todo hijo es un XMLNode que puede ser del tipo Element, Text, Attribute, etc. 48
Xml. Text. Reader n n n Frente al estándar SAX, . NET ofrece Xml. Text. Reader Está basado en streams como SAX y es por tanto más eficiente con el uso de memoria que DOM Usa un mecanismo pull para examinar XML en vez de push como SAX 49
Ejemplo Xml. Text. Reader I n Lee un fichero XML y visualiza todos sus nodos <? xml version="1. 0"? > <!-- This is a sample XML document --> <!DOCTYPE Items [<!ENTITY number "123">]> <Items> <Item>Test with an entity: &number; </Item> <Item>test with a child element <more/> stuff</Item> <Item>test with a CDATA section <![CDATA[<456>]]> def</Item> <Item>Test with an char entity: A </Item> <!-- Fourteen chars in this element. --> <Item>1234567890 ABCD</Item> </Items> 50
Ejemplo Xml. Text. Reader II public class Sample { private const String filename = "items. xml"; public static void Main() { Xml. Text. Reader reader = null; try { // Cargar reader con fichero XML ignorando espacios. reader = new Xml. Text. Reader(filename); reader. Whitespace. Handling = Whitespace. Handling. None; // Procesar fichero y visualizar cada nodo while (reader. Read()) { switch (reader. Node. Type) { case Xml. Node. Type. Element: Console. Write("<{0}>", reader. Name); break; case Xml. Node. Type. Text: Console. Write(reader. Value); break; case Xml. Node. Type. CDATA: Console. Write("<![CDATA[{0}]]>", reader. Value); break; 51
Ejemplo Xml. Text. Reader III case Xml. Node. Type. Processing. Instruction: Console. Write("<? {0} {1}? >", reader. Name, reader. Value); break; case Xml. Node. Type. Comment: Console. Write("<!--{0}-->", reader. Value); break; case Xml. Node. Type. Xml. Declaration: Console. Write("<? xml version='1. 0'? >"); break; case Xml. Node. Type. Document: break; case Xml. Node. Type. Document. Type: Console. Write("<!DOCTYPE {0} [{1}]", reader. Name, reader. Value); break; 52
Ejemplo Xml. Text. Reader IV case Xml. Node. Type. Entity. Reference: Console. Write(reader. Name); break; case Xml. Node. Type. End. Element: Console. Write("</{0}>", reader. Name); break; } } } finally { if (reader!=null) reader. Close(); } } } // Final clase 53
Transformaciones XSLT n n XSLT (Extensible Stylesheet Language Transformations) es un lenguaje para convertir documentos XML de un formato en otro Tiene dos usos principales: ¨ Convertir documentos XML en HTML ¨ Convertir documentos XML en otros documentos XML l Este tipo de conversiones son el núcleo de aplicaciones middleware como Microsoft Biz. Talk Server. 54
Ejemplo transformación XSLT using System; using System. Xml. XPath; using System. Xml. Xsl; class My. App { static void Main (string[] args) { if (args. Length < 2) { Console. Write. Line ("Syntax: TRANSFORM xmldoc xsldoc"); return; } try { Xsl. Compiled. Transform xsl = new Xsl. Compiled. Transform (); xsl. Load (args[1]); 55
Ejemplo transformación XSLT //Crear un nuevo XPath. Document y cargar el fichero XML a transformar XPath. Document doc = new XPath. Document (args[0]); //Crear un Xml. Text. Writer que escribe a consola. Xml. Writer writer = new Xml. Text. Writer(Console. Out); xsl. Transform (doc, null, writer, null); } catch (Exception ex) { Console. Write. Line (ex. Message); } } } 56
W 3 C Document Object Model (DOM) n n n Documentos XML son tratados como un árbol de nodos Cada elemento es un “nodo” Los elementos hijos y el texto contenido dentro de un elemento son subnodos W 3 C DOM Site: http: //www. w 3. org/DOM/ DOM Java Language Binding: http: //www. w 3. org/TR/DOM-Level-2 -Core/javabinding. html 57
Características DOM n Documento que se carga totalmente en memoria en una estructura de árbol n Ventaja: fácil acceder a datos en función de la jerarquía de elementos, así como modificar el contenido de los documentos e incluso crearlos desde cero. n Desventaja: coste en tiempo y memoria que conlleva construir el árbol 58
W 3 C XML DOM Objects n n n Element – un elemento XML Attribute – un attributo Text – texto contenido en un elemento o atributo CDATAsection – sección CDATA Entity. Reference – Referencia a una entidad Entity – Indicación de una entidad XML Processing. Instruction – Una instrucción de procesamiento Comment – Contenido de un comentario de XML Document – El objeto documento Document. Type – Referencia al elemento DOCTYPE Document. Fragment – Referencia a fragmento de documento Notation – Contenedor de una anotación 59
DOM <? xml version="1. 0"? > <Guitars> <Guitar Image="My. SG. jpeg"> <Make>Gibson</Make> <Model>SG</Model> <Year>1977</Year> <Color>Tobacco Sunburst</Color> <Neck>Rosewood</Neck> </Guitars> 60
Árbol DOM 61
XMLDocument I n n La clase XMLDocument es compatible con la especificación DOM Level 2 Core Representa a un documento como un árbol de nodos que tiene por raíz el elemento raíz del documento XML. Cada nodo es una instancia de Xml. Node, que expone métodos y propiedades para navegar árboles DOM, leer y escribir contenido de nodos, añadir y borrar nodos, etc. Un ejemplo sencillo de su uso sería: Xml. Document doc = new Xml. Document (); doc. Load ("Guitars. xml"); n n El atributo Document. Element devuelve un Xml. Node que hace referencia a la raíz del documento, que es el punto de comienzo al navegar de arriba a abajo el árbol DOM La combinación de los atributos Has. Child. Nodes y Child. Nodes hace posible un enfoque recursivo para iterar sobre los nodos de un árbol La invocación a Child. Nodes no devuelve atributos XML, sin embargo, su propiedad Attributes lo hace. Las propiedades Node. Type, Name, y Value de un Xml. Node exponen su tipo, nombre, y valor del correspondiente nodo ¨ En atributos usa la propiedad Local. Name para devolver nombres sin prefijos. 62
XMLDocument II n n n Para acceder a nodos particulares puedes hacer uso de las propiedades de un Xml. Document Get. Elements. By. Tag. Name, Select. Nodes, y Select. Single. Node Xml. Document puede también utilizarse para escribir documentos XML La clase Xml. Data. Document ofrece un mecanismo para tratar datos relacionales como datos XML. Puedes crear un Xml. Data. Document alrededor de un Data. Set del siguiente modo: Data. Set ds = new Data. Set (); // TODO: Initialize the Data. Set with a database query Xml. Data. Document doc = new Xml. Data. Document (ds); 63
Ejemplo Xml. Document I using System; using System. Xml; class My. App { static void Main () { Xml. Document doc = new Xml. Document (); doc. Load ("Guitars. xml"); Xml. Node. List nodes = doc. Get. Elements. By. Tag. Name ("Guitar"); foreach (Xml. Node node in nodes) { Console. Write. Line ("{0} {1}", node["Make"]. Inner. Text, node["Model"]. Inner. Text); } // Visualiza el contenido de todo el árbol Output. Node (doc. Document. Element); } 64
Ejemplo Xml. Document II public static void Output. Node (Xml. Node node) { Console. Write. Line ("Type={0}t. Name={1}t. Value={2}", node. Node. Type, node. Name, node. Value); if (node. Attributes != null) { foreach (Xml. Attribute attr in node. Attributes) Console. Write. Line("Type={0}t. Name={1}t. Value={2}", attr. Node. Type, attr. Name, attr. Value); } if (node. Has. Child. Nodes) { Xml. Node. List children = node. Child. Nodes; foreach (Xml. Node child in children) Output. Node (child); } } } 65
Xml. Text. Reader n La clase System. Xml. Text. Reader ofrece una interfaz rápida, hacia adelante, de sólo lectura de documentos XML. ¨ ¨ ¨ Xml. Validating. Reader permite efectuar una validación de un documento XML Es orientada al stream como SAX Es más eficiente en consumo de memoria que Xml. Document, Xml. Text. Reader reader = null; . . . reader = new Xml. Text. Reader ("Guitars. xml"); reader. Whitespace. Handling = Whitespace. Handling. None; while (reader. Read ()) { Console. Write. Line ("Type={0}t. Name={1}t. Value={2}", reader. Node. Type, reader. Name, reader. Value); if (reader. Attribute. Count > 0) { while (reader. Move. To. Next. Attribute()) { Console. Write. Line ("Type={0}t. Name={1}t. Value={2}", reader. Node. Type, reader. Name, reader. Value); } } 66
Xml. Text. Writer n La clase Xml. Text. Writer se puede utilizar para generar documentos Xml desde cero. Xml. Text. Writer writer = null; . . . writer = new Xml. Text. Writer ("Guitars. xml", System. Text. Encoding. Unicode); writer. Formatting = Formatting. Indented; writer. Write. Start. Document (); writer. Write. Start. Element ("Guitars"); writer. Write. Start. Element ("Guitar"); writer. Write. Attribute. String ("Image", "My. SG. jpeg"); writer. Write. Element. String ("Make", "Gibson"); writer. Write. Element. String ("Model", "SG"); writer. Write. Element. String ("Year", "1977"); writer. Write. Element. String ("Color", "Tobacco Sunburst"); writer. Write. Element. String ("Neck", "Rosewood"); writer. Write. End. Element (); 67
XPath n n XPath o XML Path Language, es un lenguaje para acceder a partes de un documento XML XPath puede ser considerado con el equivalente XML de SQL El espacio de nombres System. Xml. XPath define un conjunto de clases que permiten su uso Algunos ejemplos de location path son: ¨ ¨ ¨ ¨ Todos los elementos Guitar que son hijos de Guitars: /Guitars/Guitar Todos los atributos (no elementos) de nombre Image que pertenecen a elementos Guitar: /Guitars/Guitar/@Image Todos los elementos Guitar en el documento: //Guitar Todos los elementos hijo de Guitars: /Guitars/* Todos los atributos que pertenecen a elementos Guitar en el documento: //Guitar/@* Elementos Guitar que tienen atributo Image: //Guitar[@Image] Todos los elementos Guitar que tienen atributo Image con valor “My. Strat. jpeg”: //Guitar[@Image = "My. Strat. jpeg"] Guitarras manufacturadas después de 1980 por Fender: //Guitar[Year > 1980][Make = "Fender"] o //Guitar[Year > 1980 and Make = "Fender"] 68
System. Xml. XPath n Las clases principales de este espacio de nombres son: XPath. Document, representa documentos XML que quieren ser consultados mediante XPath ¨ XPath. Navigator, provee un mecanismo para ejecutar consultas XPath; ¨ XPath. Node. Iterator, que representa conjuntos de nodos generados por consultas XPath y permite iterar sobre ellos ¨ n XPath. Navigator provee 5 métodos para ejecutar consultas XPath. ¨ Los más importantes son: l l n Evaluate ejecuta cualquier expresión XPath, devolviendo un Object que puede ser un string, un float, un boolean o un XPath. Node. Iterator Select trabaja exclusivamente con expresiones que devuelven conjuntos de nodos y es un vehículo ideal para evaluar location paths. Siempre devuelve un XPath. Node. Iterator es una clase simple que puedes utilizar para iterar por los elementos devueltos en un node set. La propiedad Count devuelve cuántos nodos han sido devueltos: Console. Write. Line ("Select returned {0} nodes", iterator. Count); ¨ El método Move. Next te permite iterar por el conjunto de nodos. Mientras iteras, la propiedad Current expone un objeto XPath. Navigator que representa el nodo actual. ¨ 69
Ejemplo XPath using System; using System. Xml. XPath; class My. App { static void Main () { XPath. Document doc = new XPath. Document ("Guitars. xml"); XPath. Navigator nav = doc. Create. Navigator (); XPath. Node. Iterator iterator = nav. Select ("/Guitars/Guitar"); while (iterator. Move. Next ()) { XPath. Node. Iterator it = iterator. Current. Select ("Make"); it. Move. Next (); string make = it. Current. Value; it = iterator. Current. Select ("Model"); it. Move. Next (); string model = it. Current. Value; Console. Write. Line ("{0} {1}", make, model); } } } 70
Extensible Style Language Transformations (XSLT) I n Con la diversidad de lenguajes de presentación que hay (WML, HTML, c. HTML) existen dos alternativas para desarrollar las aplicaciones: ¨ Desarrollar versiones de los procesos de generación de presentación (JSP, ASP, CGI, . . ) para cada lenguaje. ¨ Desarrollar solo una versión que genere XML y conversores de XML a los lenguajes de presentación. 71
Extensible Style Language Transformations (XSLT) II n Dos partes: Transformation Language (XSLT) ¨ Formatting Language (XSL Formatting Objects) ¨ n n n XSLT transforma un documento XML en otro documento XML XSLFO formatea y estiliza documentos en varios modos XSLT W 3 C Recommendation - http: //www. w 3. org/TR/xslt 72
Operaciones entre árboles en XSL 73
Ventajas y desventajas de XSLT n Ventajas: No asume un único formato de salida de documentos ¨ Permite manipular de muy diversas maneras un documento XML: reordenar elementos, filtrar, añadir, borrar, etc. ¨ Permite acceder a todo el documento XML ¨ XSLT es un lenguaje XML ¨ n Desventajas: Su utilización es más compleja que un lenguaje de programación convencional ¨ Consume cierta memoria y capacidad de proceso DOM detrás ¨ 74
Usando hojas de estilo XSLT n Para crear una transformación XSL necesitamos: ¨ El documento XML a transformar (students. xml) ¨ La hoja de estilo que especifica la transformación (students. xsl) 75
Documento XML (students. xml) <? xml version="1. 0"? > <? xml-stylesheet type="text/xsl" href=“students. xsl"? > <course> <name id="csci_2962">Programming XML in Java</name> <teacher id=“di">Diego Ipiña</teacher> <student id=“ua"> <name>Usue Artaza</name> <hw 1>30</hw 1> <hw 2>70</hw 2> <project>80</project> <final>85</final> </student> <student id=“iu"> <name>Iñigo Urrutia</name> <hw 1>80</hw 1> <hw 2>90</hw 2> <project>100</project> <final>40</final> </student> </course> 76
Hoja de estilo XSLT (students. xsl) <? xml version="1. 0"? > <xsl: stylesheet version="1. 0“ xmlns: xsl="http: //www. w 3. 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> 77
Resultado de transformación n (students. html) <HTML> <HEAD> <TITLE>Name of students</TITLE> </HEAD> <BODY> <P>Usue Artaza</P> <P>Iñigo Urrutia</P> </BODY> </HTML> 78
Formas de uso de XSLT n n n Visualizar directamente en un navegador el documento XML que tiene asociada una hoja XSLT. Ejecutar el procesador XSLT independientemente del navegador. Se le pasan las entradas necesarias (fichero origen y hoja XSLT a utilizar) y genera la salida en un fichero, con el que podemos hacer lo queramos. Realizar las transformaciones dentro de un programa en el servidor y enviar a los clientes sólo el resultado de la transformación. 79
Aplicaciones usando XSLT Cliente Servidor XML Internet XSLT Arquitectura en 5 capas dónde el servidor contiene conversores XSLT para generar presentación en distintos formatos. JSP Clases Java Base de Datos 80
XSLT son documentos XML bien formados n n xsl: stylesheet – elemento raíz xsl: template – cómo transformar un nodo seleccionado Se asocia con un fragmento del documento a través de una expresión en XPath ¨ Transforma XML entrante en otro fragmento de XML ¨ match – Atributo para seleccionar nodo ¨ l n "/" – nodo raiz del documento de entrada Elemento xsl: apply-templates. Aplica los templates definidos para los hijos de un nodo seleccionado 81
Ejemplo XSLT <? xml version="1. 0"? > <xsl: stylesheet version="1. 0" xmlns: xsl="http: //www. w 3. org/1999/XSL/Trans form"> <xsl: template match="/"> <xsl: apply-templates/> </xsl: template> </xsl: stylesheet> 82
Elementos XSLT n xsl: value-of permite recuperar el valor de un nodo ¨ Los nodos son seleccionados usando la sintaxis de la especificación XPath XML ¨ Sólo selecciona el valor del primer estudiante que encuentre <xsl: template match=“course"> <xsl: value-of select=“student"/> </xsl: template> 83
Elementos XSLT n Si queremos seleccionar varios podemos hacer: <xsl: template match=“course"> <xsl: apply-templates select=“student"/> </xsl: template> <xsl: template match=“student"> <xsl: value-of select=". "/> </xsl: template> n O usar xsl: for-each <xsl: template match=“course"> <xsl: for-each select=“student"> <xsl: value-of select=". "/> </xsl: for-each> </xsl: template> 84
Elementos XSLT (cont) n Para realizar distintos procesamientos en función de los datos se usa xsl: choose: ¨ Se compone de elementos xsl: when ¨ Un elemento opcional xsl: otherwise n Para procesar o no un elemento en función de una condición se usa xsl: if: ¨ Condición en atributo test 85
Ejemplo <? xml version="1. 0"? > <xsl: stylesheet version="1. 0" xmlns: xsl="http: //www. w 3. 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> 86
Patrones XPath para el atributo match o select n Seleccionar el nodo raiz: <xsl: template match="/">. . . </xsl: template> n Seleccionar un elemento: <xsl: template match="student">. . . </xsl: template> n Seleccionar hijos de un elemento: <xsl: template match="course/student">. . . </xsl: template> <xsl: template match="course/*/name">. . . </xsl: template> n Seleccionar descendientes de un elemento: <xsl: template match="course//name">. . . </xsl: template> 87
Patrones XPath para el atributo match o select n Seleccionar atributo título: <xsl: value-of select=". /@id"/> n Seleccionar comentarios: <xsl: template match="comment()">. . . </xsl: template> n Seleccionar elementos de texto: <xsl: template match="text()">. . . </xsl: template> n Recuperar posición que ocupa un sub-elemento dentro de elemento padre <xsl: value-of select="position()"/> 88
Evaluando condiciones con [] n Evaluando si una condición es cierta: Si el elemento estudiante tiene un hijo name <xsl: template match="student[name]"> ¨ Cualquier elemento que tiene un elemento name <xsl: template match="*[name]"> ¨ Elemento student tiene un sub-elemento hw 1 o hw 2 element <xsl: template match="student[hw 1 | hw 2]"> ¨ 89
Ejemplo XSLT Problema: Imprimir nombre de alumnos con nota media mayor de 65% <? xml version="1. 0"? > <xsl: stylesheet version="1. 0" xmlns: xsl="http: //www. w 3. 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="(hw 1 + hw 2 + project + final) div 4"/> </xsl: variable> <xsl: if test="$ave > 65"> Student name="<xsl: value-of select="name"/>" average="<xsl: value-of select="$ave"/>" </xsl: if> </xsl: template> </xsl: stylesheet> 90
Resultado transformación n Salida (grades 70. txt): Student name=“Usue Artaza" average="66, 25" Student name=“Iñigo Urrutia" average="77, 5" 91
XSLT en. NET n n n XSLT (Extensible Stylesheet Language Transformations ) es la herramienta de tratamiento estrella de XML. XSLT es un lenguaje de programación para convertir documentos XML de un formato a otro. XSLT tiene dos usos principales: Convertir documentos XML en HTML: útil para construir páginas web y otros documentos XML dirigidos a browsers ¨ Convertir documentos XML en otros documentos XML ¨ l n Las conversiones XSLT XML-a-XML son el núcleo de aplicaciones middleware como Microsoft Biz. Talk Server que automatizan los procesos de negocio orquestrando el flujo de información La clase System. Xml. Xsl. Compiled. Transform nos permite efectuar transformaciones XSLT. 92
XSLT n La figura ilustra el funcionamiento de XSLT. Se necesita: Un documento fuente XML a transformar ¨ Un documento XSL que describe cómo el procesador XSLT debe transformar el documento ¨ 93
Aplicando XSL en el Cliente I <!– guitars. xml --> <? xml version="1. 0"? > <? xml-stylesheet type="text/xsl" href="Guitars. xsl"? > <Guitars> <Guitar> <Make>Gibson</Make> <Model>SG</Model> <Year>1977</Year> <Color>Tobacco Sunburst</Color> <Neck>Rosewood</Neck> </Guitar> <Make>Fender</Make> <Model>Stratocaster</Model> <Year>1990</Year> <Color>Black</Color> <Neck>Maple</Neck> </Guitars> 94
Aplicando XSL en el Cliente II // guitars. xsl <? xml version="1. 0"? > <xsl: stylesheet xmlns: xsl="http: //www. w 3. org/1999/XSL/Transform" version="1. 0"> <xsl: template match="/"> <html> <body> <h 1>My Guitars</h 1> <hr /> <table width="100%" border="1"> <tr bgcolor="gainsboro"> <td><b>Make</b></td> <td><b>Model</b></td> <td><b>Year</b></td> <td><b>Color</b></td> <td><b>Neck</b></td> </tr> 95
Aplicando XSL en el Cliente II <xsl: for-each select="Guitars/Guitar"> <tr> <td><xsl: value-of select="Make" /></td> <td><xsl: value-of select="Model" /></td> <td><xsl: value-of select="Year" /></td> <td><xsl: value-of select="Color" /></td> <td><xsl: value-of select="Neck" /></td> </tr> </xsl: for-each> </table> </body> </html> </xsl: template> </xsl: stylesheet> 96
Aplicando XSL en el Cliente III 97
Aplicando XSL en el Servidor I <!-- quotes. xml --> <? xml version="1. 0"? > <Quotes> <Quote> <Text>Give me chastity and continence, but not yet. </Text> <Author>Saint Augustine</Author> </Quote> <Text>The use of COBOL cripples the mind; its teaching should therefore be regarded as a criminal offense. </Text> <Author>Edsger Dijkstra</Author> </Quote> <Text>C makes it easy to shoot yourself in the foot; C++ makes it harder, but when you do, it blows away your whole leg. </Text> <Author>Bjarne Stroustrup</Author> </Quote> <Text>A programmer is a device for turning coffee into code. </Text> <Author>Jeff Prosise (with an assist from Paul Erdos)</Author> </Quote>. . . </Quotes> 98
Aplicando XSL en el Servidor II <? xml version="1. 0"? > <!-- quotes. xsl --> <xsl: stylesheet xmlns: xsl="http: //www. w 3. org/1999/XSL/Transform" version="1. 0"> <xsl: template match="/"> <html> <body> <h 1 style="background-color: teal; color: white; font-size: 24 pt; text-align: center; letter-spacing: 1. 0 em"> Famous Quotes </h 1> <table border="1"> <tr style="font-size: 12 pt; font-family: verdana; font-weight: bold"> <td style="text-align: center">Quote</td> <td style="text-align: center">Author</td> </tr> <xsl: for-each select="Quotes/Quote"> <xsl: sort select="Author" /> <tr style="font-size: 10 pt; font-family: verdana"> <td><xsl: value-of select="Text"/></td> <td><i><xsl: value-of select="Author"/></i></td> </tr> </xsl: for-each> </table> </body> </html> </xsl: template> </xsl: stylesheet> 99
Aplicando XSL en el Servidor III <!-- quotes. aspx --> <%@ Page Language="C#" %> <%@ Import Namespace="System. Xml. XPath" %> <%@ Import Namespace="System. Xml. Xsl" %> <% XPath. Document doc = new XPath. Document (Server. Map. Path ("Quotes. xml")); Xsl. Transform xsl = new Xsl. Transform (); xsl. Load (Server. Map. Path ("Quotes. xsl")); xsl. Transform (doc, null, Response. Output. Stream); %> 100
Aplicando XSL en el Servidor IV 101
Transform. cs using System; using System. Xml. XPath; using System. Xml. Xsl; class My. App { static void Main (string[] args) { if (args. Length < 2) { Console. Write. Line ("Syntax: TRANSFORM xmldoc xsldoc"); return; } try { XPath. Document doc = new XPath. Document (args[0]); Xsl. Transform xsl = new Xsl. Transform (); xsl. Load (args[1]); xsl. Transform (doc, null, Console. Out); } catch (Exception ex) { Console. Write. Line (ex. Message); } } } 102
XSLT Object Extensions n La clase System. Xml. Xsl. Compiled. Transform provee dos mecanismos para crear extensiones de usuario: ¨ Las páginas XSLT pueden contener funciones escritas en C#, VB. NET o Java. Script dentro de elementos msxml: script l ¨ Usar objetos de extensión XSLT l n Pueden invocarse desde dentro de la hoja de estilo Objetos cuyos métodos públicos son accesibles desde la hoja de estilo una vez añadidos al objeto Xsl. Transform mediante el método Add. Extension. Object Ventajas objetos de extensión XSLT: Desacoplan las extensiones de una página concreta ¨ Pueden reutilizarse tales extensiones ¨ 103
XSL Scripts n n Solamente funciona para IE Documentación en: http: //msdn 2. microsoft. com/en -us/library/ms 256042(VS. 80). aspx Elemento a utilizar msxsl: script Ejemplo XML: <? xml version="1. 0" ? > <? xml-stylesheet type="text/xsl" href="Xsl. Script. Example. xsl"? > <prueba/> 104
XSL Scripts n Ejemplo XSL: <? xml version="1. 0"? > <xsl: stylesheet xmlns: xsl="http: //www. w 3. org/1999/XSL/Transform" xmlns: msxsl="urn: schemas-microsoft-com: xslt" xmlns: user="http: //mycompany. com/mynamespace" version="1. 0"> <xsl: template match="/"> <xsl: value-of select="user: xml(. )"/> <xsl: value-of select="user: clock()"/> </xsl: template> <msxsl: script language="Java. Script" implements-prefix="user"> <![CDATA[ function xml(nodelist) { return nodelist. next. Node(). xml; } ]]> </msxsl: script> 105
XSL Scripts <msxsl: script language="Java. Script" implements-prefix="user"> <![CDATA[ function clock() { var time = new Date(); var hours = time. get. Hours(); var min = time. get. Minutes(); var sec = time. get. Seconds(); var status = "AM"; if (hours > 11) { status = "PM"; } if (hours < 11) { hours -= 12; } if (min < 10) { min = "0" + min; } if (sec < 10) { sec = "0" + sec; } return hours + ": " + min + ": " + sec + " " + status; } ]]> </msxsl: script> </xsl: stylesheet> 106
Transformación con Java. Script <html> <body> <script type="text/javascript">// Load XML var xml = new Active. XObject("Microsoft. XMLDOM") xml. async = false xml. load("cdcatalog. xml")// Load XSL var xsl = new Active. XObject("Microsoft. XMLDOM") xsl. async = false xsl. load("cdcatalog. xsl")// Transform document. write(xml. transform. Node(xsl)) </script> </body> </html> 107
XSLT Object Extensions n Microsoft recomienda evitar el uso de scripts inline en hojas XSLT ¨ Para implementar funcionalidad extra es mejor utilizar códigos de bloque externos l Revisar ejemplo en las siguientes transparencias 108
Ejemplo Extensions Object // Compile: csc /target: library Products. cs using System; using System. Data. Sql. Client; namespace Inventory. Extension. Object { public class Products { Sql. Connection cn; public Products() { cn = new Sql. Connection(@"server=localhostSQLEXPRESS; database=northwind; uid=sa; pwd=distributed. net"); cn. Open(); } public int Get. Current. Stock. Level(int Product. Id) { Sql. Command cmd = new Sql. Command("Select Units. In. Stock from Products where" + " Product. ID = " + Product. Id, cn); int Units. In. Stock = Convert. To. Int 32(cmd. Execute. Scalar()); return Units. In. Stock; } public void Dispose() { cn. Close(); } } } 109
Products. xml <? xml version="1. 0" encoding="ISO-8859 -1" ? > <Products> <Product id="1" name=“chorizo"/> <Product id="2" name=“jamón"/> <Product id="3" name=“salami"/> </Products> 110
Products. xsl <? xml version='1. 0' encoding="ISO-8859 -1" ? > <!-- Notice how a namespace URI and prefix are declared to reference EO --> <xsl: stylesheet xmlns: xsl="http: //www. w 3. org/1999/XSL/Transform" version="1. 0" xmlns: Inventory. Extension. Obj="urn: Inventory. Extension. Obj"> <xsl: template match="Products"> <HTML> <BODY> <H 3>Ipiña Altzariak</H 3><BR/> <TABLE BORDER="1"> <TR> <TH>Product Id</TH> <TH>Product Name</TH> <TH>Units In Stock</TH> </TR> <xsl: for-each select="Product"> <TR> <TD><xsl: value-of select="@id"/></TD> <TD><xsl: value-of select="@name"/></TD> <!-- call extension object method to retrieve stock information --> <TD><xsl: value-of select="Inventory. Extension. Obj: Get. Current. Stock. Level(@id)"/></TD> </TR> </xsl: for-each> </TABLE> </BODY> </HTML> </xsl: template> </xsl: stylesheet> 111
Ejemplo Aplicación usando EO // Compile: csc /r: Products. dll Products. Stock. Level. cs using System; using System. Text; using System. Xml. XPath; using System. Xml. Xsl; namespace Inventory. Extension. Object { public class Products. Stock. Level { public static void Main(string [] args) { try { XPath. Document xml. Doc = new XPath. Document("products. xml"); // Instantiate a new Xsl. Transform object and load the style sheet. Xsl. Compiled. Transform xslt = new Xsl. Compiled. Transform(); xslt. Load("products. xsl"); // Instantiate an Xslt. Argument. List object. // An Xslt. Argument. List object is used to supply extension object instances // and values for XSLT paarmeters required for an XSLT. transformation Xslt. Argument. List xslt. Arg. List = new Xslt. Argument. List(); //Instantiate and Add an instance of extension object to Xslt. Argument. List. Inventory. Extension. Object. Products Inventory. Extension. Obj = new Inventory. Extension. Object. Products(); xslt. Arg. List. Add. Extension. Object("urn: Inventory. Extension. Obj", Inventory. Extension. Obj); 112
Ejemplo Aplicación usando EO // Execute the transformation and generate the output to results. html Xml. Writer. Settings settings = new Xml. Writer. Settings(); settings. Encoding = Encoding. Get. Encoding("iso-8859 -1"); Xml. Writer xml. Writer = Xml. Writer. Create("results. html", settings); xslt. Transform(xml. Doc, xslt. Arg. List, xml. Writer); Inventory. Extension. Obj. Dispose(); Inventory. Extension. Obj = null; } // Exception handling code. catch(Xslt. Compile. Exception xslt. Compile. Exp) { Console. Write. Line(xslt. Compile. Exp. Message); } catch(Xslt. Exception xslt. Exp) { Console. Write. Line(xslt. Exp. Message); } catch(XPath. Exception XPath. Exp) { Console. Write. Line(XPath. Exp. Message); } catch(Xml. Exception Xml. Exp) { Console. Write. Line(Xml. Exp. Message); } } 113
EXSLT n Iniciativa para proporcionar extensiones a XSLT ¨ n n http: //www. exslt. org/ Objetivo: extender su uso entre los implementadores de motores XSLT para incrementar la portabilidad de hojas XSLT Define los siguientes módulos: ¨ ¨ ¨ Common EXSLT: exsl: node-set, exsl: object-type Math EXSLT: math: min, math: max, math: highest, math: abs, math: random Sets EXSLT: set: difference, set: intersection, set: distinct Dates and Times EXSLT: date-time, date: month-name, date: seconds Strings EXSLT: str: tokenize, str: replace Regular Expressions EXSLT: regexp: test, regexp: match, regexp: replace 114
XSLT Object Extensions n Es una implementación de las extensiones EXSLT para XSLT 1. 0 para la framework. NET: ¨ Web: http: //mvp-xml. sourceforge. net/exslt/ ¨ Download: http: //sourceforge. net/project/showfiles. php? group_id= 102352 ¨ Ejemplos interesantes: http: //msdn 2. microsoft. com/enus/library/ms 950776. aspx ¨ EXSLT: iniciativa para crear extensiones para XSLT 115
XSLT Object Extensions //Create the Xsl. Transform and load the stylesheet. Xsl. Transform xslt = new Xsl. Transform(); xslt. Load("test. xsl"); //Load the XML data file. XPath. Document doc = new XPath. Document("test. xml"); //Create an Xslt. Argument. List and add the EXSLT object for the math functions Xslt. Argument. List xsl. Arg = new Xslt. Argument. List(); xsl. Arg. Add. Extension. Object("http: //exslt. org/math", new Exslt. Math()); //Create an Xml. Text. Writer to output to the console. Xml. Text. Writer writer = new Xml. Text. Writer(Console. Out); //Transform the file. xslt. Transform(doc, xsl. Arg, writer, null); writer. Close(); 116
Conclusión n n Las clases en el espacio de nombres System. Xml simplifican la lectura, escritura y manipulación de documentos XML Miembros destacados de System. Xml son: Xml. Document, que provee una interfaz DOM a documentos XML Xml. Text. Reader y Xml. Validating. Reader, que combina la eficiencia de SAX con un modelo sencillo PULL para leer XML y validarlo opcionalmente ¨ Xml. Text. Writer, que escribe documentos Xml ¨ XPath. Document, XPath. Navigator, y XPath. Node. Iterator, que permiten la realización de consultas XPath en documentos Xml e iterar sobre los resultados ¨ Xsl. Compiled. Transform, que efectúa transformaciones XSL en datos XML. ¨ ¨ n XML es una realidad del desarrollo software actual ¨ La FCL de. NET nos simplifica este proceso 117
Referencias n XML DOM Tutorial ¨ n XSLT Tutorial ¨ n http: //msdn 2. microsoft. com/en-us/library/ms 950776. aspx Ejemplos interesantes de uso de EXSLT: ¨ n http: //support. microsoft. com/kb/323370 EXSLT: Enhancing the Power of XSLT ¨ n http: //www. w 3 schools. com/xsl/default. asp HOW TO: Use Extension Objects When You Execute XSL Transformations in Visual C#. NET Applications ¨ n http: //www. w 3 schools. com/default. asp http: //msdn 2. microsoft. com/en-us/library/ms 950776. aspx Nuevas características. NET XML 2. 0: ¨ http: //www. 15 seconds. com/issue/050601. htm 118
XML, Distribución y Componentes Tema 1 – Procesamiento XML en. NET – Preguntas y Sugerencias Dr. Diego Lz. de Ipiña Gz. de Artaza http: //paginaspersonales. deusto. es/dipina (Personal) http: //www. morelab. deusto. es (Research Group) http: //www. smartlab. deusto. es (Research Lab) http: //www. ctme. deusto. es (Cátedra de Telefónica Móviles) http: //www. tecnologico. deusto. es (Tecnológico-Fundación Deusto) Fundación Deusto - Tecnológico Deusto
- Slides: 119