Equipos Programas Media Internet Telecomunicaciones Seguridad Base de Datos Programación Calidad Desarrollo Empresa

XML Tutorial

Tabla de Contenido

  1. Introducción a XML
  2. XML Conceptos
    1. Particularidades del documento XML
    2. XML vs HTML y Texto plano
    3. Notas 1
    4. Notas 2
  3. XML Sintaxis
    1. Componentes
    2. El comentario
    3. Xpath - Elementos de búsqueda
    4. Xpath - Predicado
    5. Xpath - Ejemplos
  4. XML Varios
    1. El XML entendido como comunicacion web
    2. DOM - Programacion con XML
    3. DOM - Ejemplos DOM API

Contenido

  • Introducción a XML

    Conocer el lenguaje XML

    • XSL es un lenguaje para hojas de estilo. Consiste en tres partes:

    • Transformaciones XSL (XSLT). Lenguaje para transformar documentos XML.

    • Lenguajes de path (ruta) XML (XPath). Lenguaje usado por XSLT para acceder o referirse a partes de un documento XML. (También es usado por la espacificación de XML linking.

    • Objetos de formateo XSL (Formating objects). Vocabulario XML para especificar semánticas de formateo.

    • Una hoja de estilo XSL especifica la representación de una clase de documento XML, describiendo como una instancia de dicha clase es transformada en un documento XML que usa el vocabulario de formateo.
  • XML Conceptos

    • Particularidades del documento XML

      El fichero XML

      • Es auto descriptivo
      • No hace nada, solo contiene datos.
      • Sirve para intercambiar datos.
      • Definimos nuestros propios tag.
      • Cada tag debe cerrarse obligatoriamente, y además debe hacerse por orden..
      • Los tag son sensibles a mayúsculas y minúsculas.
      • Debe tener un tag raíz o root.
      • Los elementos están anidados.
      • No se eliminan automáticamente los espacios en blanco.
      • Si queremos que se reconozcan caracteres latinos la primera línea debe ser <?xml version='1.0' encoding='ISO-8859-1'?>
      • Los caracteres (<), (>) y (') deben representarse como (&lt;), (&gt;) y (&quot;) en el texto, ya que son caracteres especiales o tokens del XML.
      • Los valores de los atributos siempre deben ir entre comillas.
      • Los saltos de línea siempre se guardan como LF (line feed).
      • Los comentarios van entre los tag <!-- Comentario -->
      • En el navegador podemos expandir o colapsar los distintos niveles del árbol.

    • XML vs HTML y Texto plano

      Ventajas del XML respecto a HTML

      • Texto
        • Las personas no necesitan códigos o marcas (tags) para leer un texto. Ej: obra de teatro.
        • Han aprendido en la escuela a identificar y asignar el significado a los distintos pasajes del texto

      • HTML
        • Las marcas (tags) de HTML definen como se representa el texto en el navegador.
        • No añade semántica y por tanto no es posible inferir información sobre el contenido Ej.: ¿que texto recita cada actor?

      • XML
        • Las marcas de XML se han añadido al texto
        • Un ordenador no puede derivar significado sobre el contenido
        • Un ordenador puede analizar las marcas e inferir información sobre el contenido. Ej.: extraer los actores para elaborar una lista de actores, o enviar las frases a un programa de traducción de texto a voz.
    • Notas 1

      Notas Ignacio López

      • Un archivo xml se visualiza en el Explorador según las transformaciones que realice su archivo xsl asociado.
      • Si en el archivo xml no se especifica un archivo xls, el archivo se visualiza en el Explorer tal cual, es decir, no se realiza ninguna transformación.
      • Los tags de usuario se definen en el archivo dtd
      • El archivo dtd es opcional. Si este no existe, no se pueden verificar los tags y por tanto la validez del archivo xml.
      • Según el dispositivo que acceda a un documento Web, así sera el archivo xsl asociado.
      • Los archivos xml, dtd, xsl residen en el servidor.
      • El usuario que recibe una página xml, tambien recibe el archivo xsl y es el Explorador el que produce el resultado final.
      • El usuario no tiene la posibilidad de poder asignarle en tiempo real un archivo xsl a un archivo xml, para visualizarlo con otro estilo.
      • Si un dispositivo PDA accede a una página web xml, el servidor se encarga de asociarle el archivo xsl correspondiente.
      • Los query a una base se datos se realizan en los archivos xsl.
      • Los archivos xml y dtd, los prepara un usuario sin conocimientos de informática.
      • Los archivos xsl los prepara un programador.
      • Si no se pone encoding='ISO-8859-1' en un archivo xml, xsl, xxd, dtd, y se usan los caracteres españoles: ñ, acentos, etc. dan error.
      • Encoding hay que ponerlo antes que stanalone, de lo contrario da error.
      • Siempre tiene que existir,para que este funcione., en el archivo:
    • Notas 2

      Notas Ignacio 2

      • Árbol
        • Nodos: raíz, de alto nivel, padre, hijos, ancestros y descendientes.
        • Nodo: marca de comienzo, marca de terminación, Atributos y valores

      • Tipo de árboles
        • árbol HTML
        • árbol XML
        • árbol XSL

      • Procesador XSLT
        • Localización de elementos (pattem matching)
        • Transformaciones
        • Formateo

      • Archivos
        • Página web HTML (HiperText Markup Language)
        • Hoja de estilo CSS (Cascading style sheet)
        • Página web XML (Extensible Markup Language)
        • Hoja de estilo XSL (Extensible Style Language)
        • Definición del Tipo de Documento DTD (Document Type Definition)
        • XSD: Esquema de XML (XML Schema Definition language)
  • XML Sintaxis

    • Componentes

      Componentes XML

      • El componente básico de XML es el documento o archivo. con extensión .xml, xsl, xsd. Es equivalente, en cierta forma, al módulo en un lenguaje de programación.


      • Clases de documentos XML:
        • Documento XML de datos (archivo con extensión .xml)
        • Documento XML de transformaciones (archivo con extensión .xsl)
        • Documento XML de esquema (archivo con extensión .xsd)


      • Un documento se compone de:

        • Declaración de comienzo:
          • En documentos xml:
            • <?xml version='1.0'?> o <?xml version='1.0' encoding='ISO-8859-1'?> si queremos que reconozca acentos, eñes y demás caracteres latinos.
            • <?xml-stylesheet type='text/xsl' href='tablaGeneral.xsl'?>
          • En documentos xsl:
            • <xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0'>


        • Comentarios texto que se incluye en el documento, pero no en el arbol. Un comentario comienza con los sinbolos: <!-- y termina con -->
          • Comentario de una linea: <!-- hola -->
          • Comentario de varias lineas: En cualquier posición de la primera linea se pone el simbolo de comienzo <!-- y en cualquier posición de la última linea de comentario se pone el simbolo de terminación de comentario -->
          • Los comentarios no se pueden anidar.


        • Uno o más elementos. Un elemento es un nodo del arbol Ej. de elemento
          <apellido materno='no'>Garcia<appellido>
          • Un elemento o nodo comienza con una etiqueta de comienzo de elemento Ej. <apellido> y una etiqueta de terminación.del elemento.Ej. </apellido>. o en notación simplificada <xsl:value-of select='apellido' />
            • el nombre del elemento encerrado
            • Un elemento o nodo, se compone de:
              • Nombre. Es lo que aparece en primer lugar dentro de los simbolos < > de la etiqueta. Ej.: apellido.
                • El nombre se obtiene (select) y se copia (value-of) en el arbol resultante, con la función name. Ej.: <xsl:value-of select='name(.)' />
              • Atributos son los que aparecen a continuación del nombre y son pares nombre atributo = valor atributo, separados por blancos. Ej. materno='no'.
                • Un atributo de un elemento se obtiene del arbol origen y se copia en el arbol resultante, con el simbolo @ seguido del nombre del atributo. Ej. <xsl:value-of select='apellido@materno>
                • Un atributo se define (<xsl:attribute name='materno'>) y el próximo elemento de selección lo copia (<xsl:value-of select='apellido' />) junto al elemento en el arbol resultante con: <xsl:attribute name='materno'><xsl:value-of select='apellido' />
              • Texto es lo que hay entre las etiquetas de un elemento. Ej. Garcia.
                • El texto de un nodo se obtiene (select='apellido') y copia (xsl:value-of) en el arbol de salida, con <xsl:value-of select='apellido'>
            • Los elementos pueden ser:
              • simples.
                • Notación normal: Ej. <apellido>Lopez</apellido>
                • Notación resumida: <xsl:value-of select='apellido' />
              • compuestos: engloba a varios elementos simples o compuestos.
              Ej.1: <persona>
              <nombre>Pepe</nombre>
              <edad>25</edad>
              </persona> Ej. 2: <xsl:template match='/'
              <html>
              ....
              </html>
              <xsl:template


        • Declaración de Terminación
          • En documento xml: ninguna
          • En documento xsl:
            • </xsl:stylesheet>
    • El comentario

      El Comentario en XML

      • El comentario en XML se escribe de la siguiente forma:



        • <-- Esto es un comentario en xml -->

      • Todo el texto que esté incluido dentro de un comentario, no será procesado ni aparecerá en pantalla.


      • También sirve para anular una sentencia o un trozo de página xml.
    • Xpath - Elementos de búsqueda

      Elementos de búsqueda

      . Elemento actual
      / La raíz del documento
      // Todos los elementos en cualquier lugar del documento
      .// Todos los elementos que son descendientes del contexto en curso
      nodo1 Todos los elementos que son descendientes del nodo nodo1 en el contexto en curso
      nodo1/nodo11 Todos los elementos nodo11 cuyo padre es nodo1 en el contexto en curso
      nodo1//nodonn Todos los elementos nodonn que tienen de ancestro el nodo nodo1 en el contexto en curso
      session/paran[1] El primer param hijo de todos los hijos de seccion del contexto en curso
      section/*/note Elementos <note> que tienen de abuelo <section>
      stockquote[@symbol] Elementos <stockquote> que tienen un atributo 'symbol'
      stockquote[@symbol='XXXX'] Elementos <stockquote> que tienen un atributo 'symbol' igual a 'xxxx'
      emphasis|strong Elementos emphasis o strong
    • Xpath - Predicado

      Predicado XPATH

    • La expresión que hay dentro de corchetes [ ]


    • nodetest[1] Primer nodo
      nodetest[position()=last()] Último nodo
      nodetest[position() mod 2 = 0] Nodos pares
      element[@id='foo'] Nodos elementos cuyo valor de atributo es 'foot'
  • Xpath - Ejemplos

    Ejemplos de XPath


      //atributo[nombre= 'Ejemplo']/valor'
      Encontrar todos los elementos valor, hijos del elemento atributo, tales que el texto del elemento nombre, sea igual a 'Ejemplo'

      //nombre[.='Ejemplo']
      Encontrar todos los elementos nombre cuyo texto sea igual a 'Ejemplo'

      (Basados en este archivo de ejemplo)
      ./author

      Note that this is equivalent to the following.

      author

      Find all first.name elements.

      first.name

      Find the document element (bookstore) of this document.

      /bookstore

      Find all author elements that are children of the current context node (for example, /bookstore/book).

      //author

      Find all bookstores where the value of the specialty attribute is equal to 'textbooks'.

      /bookstore[@specialty = 'textbooks']

      Find all books where the value of the style attribute on the book is equal to the value of the specialty attribute of the bookstore element at the root of the document.

      book[/bookstore/@specialty = @style]

      Find all first-name elements within an author element. Note that the author children of the current context are found, and then first-name children are found relative to the context of the author elements.

      author/first-name

      Find all title elements one or more levels deep in the bookstore (arbitrary descendants).

      bookstore//title

      Note that this is different from the following pattern, which finds all title elements that are grandchildren of bookstore elements.

      bookstore/*/title

      Find emph elements anywhere inside book excerpts, anywhere inside the bookstore.

      bookstore//book/excerpt//emph

      Find all titles one or more levels deep in the current context. Note that this situation is essentially the only one in which the period notation is required.

      .//title

      Find all element children of author elements.

      author/*

      Find all last names that are grandchildren of books.

      book/*/last-name

      Find the grandchildren elements of the current context.

      */*

      Find the book element from the 'my' namespace.

      my:book

      Find all elements from the 'my' namespace.

      my:*

      Find all elements with the specialty attribute.

      *[@specialty]

      Find the style attribute of the current element context.

      @style

      Find the exchange attribute on price elements within the current context.

      price/@exchange

      The following example does not return anything because attributes do not contain element children. It is allowed by the XML Path Language (XPath) grammar, but is not strictly valid.

      price/@exchange/total

      Find all books with style attributes.

      book[@style]

      Find the style attribute for all book elements.

      book/@style

      Find all attributes of the current element context.

      @*

      Find all attributes from the 'my' namespace. This does not include unqualified attributes on elements from the 'my' namespace.

      @my:*

      Find all first-name elements. The following examples are equivalent.

      ./first-name
      first-name

      Find all unqualified book elements.

      book

      For example, the following finds the first author element.

      author[1]

      The following finds the third author element that has a first-name.

      author[first-name][3]

      Note that indexes are relative to the parent. Consider the following data.

      <x>
      <y/>
      <y/>
      </x>
      <x>
      <y/>
      <y/>
      </x>

      Find the first y from each x.

      x/y[1]
      x/y[position() = 1]

      Find the first y from the entire set of y elements within x elements.

      (x/y)[1]

      Find the second y from the first x.

      x[1]/y[2]

      Find the last book.

      book[last()]

      Find the last author for each book.

      book/author[last()]

      Find the last author from the entire set of authors of books.

      (book/author)[last()]

      Find all books that contain at least one excerpt element.

      book[excerpt]

      Find all titles of books that contain at least one excerpt element.

      book[excerpt]/title

      Find all authors of books where the book contains at least one excerpt and the author has at least one degree.

      book[excerpt]/author[degree]

      Find all books that have authors with at least one degree.

      book[author/degree]

      Find all books that have an excerpt and a title.

      book[excerpt][title]

      Find all author elements that contain at least one degree and one award.

      author[degree and award]

      Find all author elements that contain at least one degree or award and at least one publication.

      author[(degree or award) and publication]

      Find all author elements that contain at least one degree element and that contain no publication elements.

      author[degree and not(publication)]

      Find all author elements that contain publication elements but do not contain either degree elements or award elements.

      author[not(degree or award) and publication]

      Find all author elements that contain a last-name element with the value Bob.

      author[last-name = 'Bob']

      Find all author elements where the first last-name is Bob.

      author[last-name[1] = 'Bob']
      author[last-name = 'Bob']

      Find all authors where the from attribute is not equal to 'Harvard'.

      degree[@from != 'Harvard']

      Find all authors where the last name is the same as the /guest/last-name element. (This assumes there is only one last-name. See Set Operations.)

      author[last-name = /guest/last-name]

      Find all authors whose text is 'Matthew Bob'.

      author[. = 'Matthew Bob']

      Find all author elements whose last name is 'Bob' and whose price is > 50. (This assumes there is only one last-name and price for an author. See Set Operations.)

      author[last-name = 'Bob' and price > 50]

      Find all authors whose last name begins with 'M' or greater.

      author[last-name > 'M']

      When an author can have several last names in the schema (for example, Clemens and Twain), use the following patterns.

      author[all last-name >= 'M']

      Find the first three books (1, 2, 3).

      book[position() <= 3]

      Find all author elements where any one of the last names is Bob.

      author[last-name = 'Bob']

      Find all author elements where none of the last-name elements is Bob.

      author[not(last-name = 'Bob')]

      Find all author elements containing a first-name child whose text is 'Bob'. (This and the following examples assume there is only one first-name child for an author.)

      author[first-name = 'Bob']

      Find all author elements containing any child element whose text is 'Bob'.

      author[* = 'Bob']

      Find author elements equal to 'Joe Bob'.

      author[last-name = 'Bob' and first-name = 'Joe']

      Find the intl attribute equal to 'Canada'.

      price[@intl = 'Canada']

      Find the first 3 degrees:

      degree[position() < 3]

      Find the second text node in each p element in the current context.

      p/text()[2]

      Find the nearest book ancestor of the current element.

      ancestor::book[1]

      Find the nearest ancestor author element that is contained in a book element.

      ancestor::book[author][1]

      To illustrate unions, consider the following data.

      <root>
      <x/> <!-- green -->
      <y>
      <x/> <!-- blue -->
      <x/> <!-- blue -->
      </y>
      <z>
      <x/>
      <x/>
      </z>
      <x/> <!-- green -->
      </root>

      Find both green and blue nodes.

      x | y/x
  • XML Varios


  • Página generada automáticamente desde la Base de Datos: XML/ el 28/3/2008 13:14:59