Escolar Documentos
Profissional Documentos
Cultura Documentos
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
Curso XML en Tecnologías J2EE
1. El Estándar XML
2. DOM
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
Curso XML en Tecnologías J2EE
1. El Estándar XML
2. DOM
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
Curso XML en Tecnologías J2EE
1. El Estándar XML
1.1 Introducción
1.2 Requerimientos
1.3 XML
1.4 DTDs
1.5 SAX
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
1.1 Introducción
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
Curso XML en Tecnologías J2EE
1. El Estándar XML
1.1 Introducción
1.2 Requerimientos
1.3 XML
1.4 DTDs
1.5 SAX
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
1.2 Requerimientos
PC con Windows 98 / NT / 2000, 64 MB de RAM (depende del servidor a usar)
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
Curso XML en Tecnologías J2EE
1. El Estándar XML
1.1 Introducción
1.2 Requerimientos
1.3 XML
1.4 DTDs
1.5 SAX
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
1.3 Introducción a XML
Ø Es un lenguaje de marcas
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
1.3 Características XML
Ø Es “case sensitive”
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
1.3 Ejemplo
<?xml version="1.0"?>
<!DOCTYPE discos SYSTEM "cds.dtd">
<discos>
<disco>
<artista tipo="individual">Frank Sinatra</artista>
<titulo numerodepistas="2">In The Wee Small Hours</titulo>
<pistas>
<pista>In The Wee Small Hours</pista>
<pista>Mood Indigo</pista>
</pistas>
<precio>$12.99</precio>
</disco>
<disco>
<artista tipo="band">The Offspring</artista>
<titulo numerodepistas="2">Americana</titulo>
<pistas>
<pista>Welcome</pista>
<pista>Have You Ever</pista>
</pistas>
<precio>$12.99</precio>
</disco>
</discos>
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
1.3 Elementos XML
Ø Un documento XML está formado por tags o etiquetas para
la estructuración de los datos.
<pista>Welcome</pista>
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
1.3 Elementos XML - Atributos
Ø Un elemento XML puede contener uno o más atributos en su
tag inicial
Esta expresión
<precio valor=“$12.99”></precio>
equivale a
<precio valor=“$12.99”/>
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
1.3 Documentos XML
Un documento XML es un conjunto de elementos XML anidados
(con estructura de árbol)
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
1.3 Reglas de Construcción
de Nombres XML
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
1.3 Documento XML Bien Formado
Se dice que un documento XML está bien formado si cumple las
siguientes reglas:
Ø Todo tag debe tener su correspondiente tag final.
Ø Los elementos deben quedar debidamente anidados
Ø Debe haber exactamente un elemento raíz
Ø Los valores de los atributos deben estar entre comillas
Ø Un mismo elemento no debe tener más de un atributo con el
mismo nombre
Ø Los comentarios no deben colocarse dentro de los tags
Ø Los caracteres & y < deben ser precedidos por un \ si
forman parte de los datos de un elemento o atributo.
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
1.3 XML – Ejercicio 1
¿Es el siguiente documento XML un documento bien formado?
<empleado>
<empleado nombre=“Juan” apellido=“Pérez” apellido=“Sánchez”>
<direccion calle=“López Peñalver”>
</empleado>
<Empleado nombre=“Alberto”>
<direccion calle=“López Peñalver”>
</Empleado>
<empleado>
<localidad>Málaga<localidad>
</Empleado>
</empleados>
<oficinas>
<oficina 1tlf=“951000000” 2tlf=“951000001”>
<ciudad>Madrid</ciudad>
</oficina>
<oficina>
<ciudad telefono=“12312312”>Barcelona</ciudad>
</oficina>
</oficinas>
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
1.3 XML – Ejercicio 2
Crear un documento XML válido que contenga los siguientes datos:
1122 IB888
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
1.3 XML - Namespaces
Ø Un XML namespace es una colección de nombres que pueden ser
usados en elementos o atributos.
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
1.3 XML – Namespaces - Declaración
Se declara con el atributo xmlns en el elemento deseado.
Existen dos tipos de declaración:
<BOOK xmlns="urn:BookLovers.org:BookInfo">
<TITLE>A Suitable Boy</TITLE>
<PRICE currency="US Dollar">22.95</PRICE>
</BOOK>
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
1.3 Prólogo del Documento XML
Antes del elemento raíz del documento XML pueden aparecer una serie
de elementos, formando la siguiente estructura:
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
1.3 Prólogo del Documento XML
Declaración
Comentarios
<!--
Discos.xml, ejemplo de documento XML
-->
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
1.3 Prólogo del Documento XML
Instrucciones de procesamiento
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
Curso XML en Tecnologías J2EE
1. El Estándar XML
1.1 Introducción
1.2 Requerimientos
1.3 XML
1.4 DTDs
1.5 SAX
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
1.4 DTDs
Ø Un DTD (Document Type Definition) es un documento que
especifica las restricciones que debe cumplir un documento XML.
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
1.4 DTDs - Declaración
Un DTD se puede declarar de 2 formas:
• En un fichero aparte
<!DOCTYPE empleado
[
<!ELEMENT empleado (nombre, direccion)>
<!ELEMENT nombre (#PCDATA)>
<!ELEMENT direccion (ciudad, calle)>
<!ELEMENT ciudad (#PCDATA)>
<!ELEMENT calle (#PCDATA)>
]
>
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
1.4 DTD – Declaración de
Elementos - Atributos
Ø Un Elemento se declara especificando su nombre y los elementos
que lo componen:
<!ELEMENT empleado (nombre, direccion)>
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
1.4 DTD – Declaración de
Elementos - Atributos
Ø Si separamos con comas los elementos hijo, el orden de
aparición de éstos debe cumplirse
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
1.4 DTD – Declaración de
Elementos - Atributos
Modificadores
+ 1 ó más
? 0ó1
Ejemplos:
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
1.4 DTD – Declaración de
Elementos - Atributos
Elementos Vacíos
Contenido ANY
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
1.4 DTD - Ejercicio
Crear un DTD que valide la siguiente estructura:
<proveedores>
<proveedor>
<nombre>Pascal</nombre>
<productos>
<producto>Leche</producto>
<producto>Flan</producto>
</productos>
</proveedor>
<proveedor>
<nombre>Capitán Pesconovo</nombre>
<productos>
<producto>Merluza</producto>
</productos>
<telefono>
952888777
</telefono>
</proveedor>
</proveedores>
Copyright Formación y Soluciones Informáticas EFIBS S.A.
31
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
1.4 DTD - Ejercicio
Crear un DTD que valide la siguiente estructura:
<clientes>
<cliente>
<nombre>Pascal</nombre>
<direccion>
<ciudad>Malaga</ciudad>
<calle>35</calle>
</direccion>
</cliente>
<cliente>
<nombre>Carlos Vega</nombre>
<direccion>
<ciudad>Esparza</ciudad>
</direccion>
<telefono>
636-65-85
</telefono>
</cliente>
</clientes>
Copyright Formación y Soluciones Informáticas EFIBS S.A.
32
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
1.4 DTD – Declaración de Atributos
Ø Un elemento puede tener 1 o más atributos. Por ejemplo, para
declarar los atributos ciudad, calle y numero del elemento direccion, se
haría de la siguiente forma:
<!ATTLIST direccion
ciudad CDATA #FIXED <direccion ciudad=“Málaga” calle=“Larios”
calle CDATA #REQUIRED numero=“5”/>
numero CDATA #IMPLIED
>
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
1.4 DTD – Declaración de Atributos
Tipos de atributos
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
1.4 DTD – Declaración de Atributos
Ø Una entidad es una asociación entre el nombre de la entidad y su valor.
La entidad puede aparecer en el valor de un elemento o atributo, y será
sustituido por su valor.
Ø Hay 5 entidades predefinidas:
< (<)
& (&)
> (>)
" (")
' (')
<empleado empresa=“&empresa;">
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
1.4 DTD – Ejercicio
Crear un DTD que valide la siguiente estructura:
<libreria3>
<libro isbn="A912546874">
<autor>Miguel De Cervantes</autor>
<titulo>El Quijote</titulo>
<precio>18</precio>
</libro>
<libro isbn="A987564511">
<autor>Antonio Lopez</autor>
<autor>Ana Perez</autor>
<titulo>Cómo crecer</titulo>
<precio>25000</precio>
<rebaja>10%</rebaja>
<resumen fichero="ert34.doc" autor=“Roger Martinez"/>
</libro>
</libreria3>
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
1.4 DTD – Ejercicio
Crear un DTD que valide la siguiente estructura:
<almacen empresa="&empresa;">
<productos>
<producto id="A191">
<nombre>Teclado</nombre>
<precio valor="20" moneda="euros"/>
<caracteristicas>15 pulgadas</caracteristicas>
</producto>
<producto id="A167">
<nombre>Monitor 14'</nombre>
<precio valor="20000" moneda="pesetas"/>
</producto>
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
Curso XML en Tecnologías J2EE
1. El Estándar XML
1.1 Introducción
1.2 Requerimientos
1.3 XML
1.4 DTDs
1.5 SAX
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
1.5 SAX
• SAX (Simple API for XML) es una API que permite a una
aplicación escribir código genérico que pueda funcionar con cualquier
parser
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
1.5 SAX
• SAX, es el Simple API para XML, tiene la característica, a diferencia
de DOM, que ha sido hecho para leer rápidamente cadenas de los
documentos XML.
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
1.5 SAX
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
1.5 SAX Ejemplo
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
1.5 SAX Ejemplo
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
Curso XML en Tecnologías J2EE
1. El Estándar XML
2. DOM
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
Curso XML en Tecnologías J2EE
2. DOM
2.1 Introducción
2.2 DOM
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
2.1 Introducción
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
2.1 Introducción
Ø El DOM (Document Object Model) es una API (Application Programming
Interface) creada para acceder a los datos de un documento XML.
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
2.1 Introducción
Ø DOM es muy flexible y genérico, además se puede hallar bastante
material en la W3C, lo cual permite mayor respaldo a la hora de la
representación sintáctica.
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
Curso XML en Tecnologías J2EE
2. DOM
2.1 Introducción
2.2 DOM
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
2.2 DOM
Ø Para poder hacer uso de la tecnología DOM, es necesario primero hacer
uso de dos clases en java fundamentales: DocumentBuilderFactory y
DocumentBuilder.
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
2.2 DOM
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
2.2 DOM – Acceso a Elementos
Ø La clase Document posee una serie de métodos útiles para obtener
información de los nodos que posee el documento XML.
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
2.2 DOM – Acceso a Elementos
Ø Node getFirstChild(): devuelve el primer elemento hijo del elemento
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
2.2 DOM – Métodos de la clase NodeList
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
2.2 DOM – Métodos de la
clase NamedNodeMap
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
2.2 DOM – Métodos de la clase Node
Ø Node appendChild(): Inserta un nuevo elemento en el nodo.
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
2.2 DOM – Métodos de la clase Node
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
2.2 DOM – Ejercicio 1
Ø Ejercicio 1.1
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
2.2 DOM – Ejercicio 1
<XML ID="XMLCliente">
<clientes>
<cliente idCliente=“81422”>
<nombre>Antonio</nombre>
</cliente>
<cliente idCliente=“81555”>
<nombre>Jose Carlos</nombre>
<localidad>San Salvador</localidad>
</cliente>
</clientes>
</XML>
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
2.2 DOM – Modificación de Elementos
Creación de un elemento
Para esto utilizamos los métodos de la clase Document
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
2.2 DOM – Modificación de Elementos
Creación de un elemento
apellido.appendChild(texto);
node.appendChild(apellido);
}
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
2.2 DOM – Modificación de Elementos
Eliminación de un elemento
NodeList listaEliminar =
document.getElementsByTagName("articulo");
Node nodoEliminar =
listaEliminar.item(listaActual.getLength()-1);
document.removeChild(nodoEliminar);
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
2.2 DOM – Modificación de Elementos
Cambiar el valor de un elemento
NodeList lista =
document.getElementsByTagName("producto");
nuevaLocalidad.appendChild(texto);
node.replaceChild(nuevaLocalidad,nodoHijo);
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
2.2 DOM – Modificación de Atributos
Cambio de valor de un atributo
Ø setAttribute(nombre,valor): si el atributo especificado existe, cambia su
valor, si no, crea uno nuevo y le asigna el valor especificado.
El siguiente ejemplo crea el atributo o lo modifica si existe de idProducto del
ultimo producto a 12345:
if(node.getNodeType() == node.ELEMENT_NODE){
element.setAttribute(“idProducto",“12345");
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
2.2 DOM – Modificación de Atributos
Eliminación de un atributo
if(node.getNodeType() == node.ELEMENT_NODE){
element.removeAttribute("idCliente");
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
2.2 DOM – Ejercicio 2
Ejercicio 2: Modificación de XML
Ejercicio 2.1
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
2.3 Crear XML en base al árbol DOM
• Para crear un documento XML en base al árbol que DOM genera en
memoria se necesita un objeto Transformer.
Ejem.:
TransformerFactory factory;
factory = TransformerFactory. newInstance();
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
2.3 Crear XML en base al árbol DOM
• Una vez que tenemos el objeto Tranformer, debemos crear un objeto
DOMSource al cual se le indica el objeto Document (raíz) con el árbol
generado por DOM.
Ejm.:
DOMSource source = DOMSource(document);
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
2.3 Crear XML en base al árbol DOM
• Seguidamente debemos crear un objeto StreamResult, el cual vamos
asociar con el archivo de salida para el futuro XML.
Ejm.:
StreamResult streamResult = new StreamResult(fos);
Ejm.:
transformer.transform(source,streamResult);
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
2.3 Ejercicio
Ejercicio 1:
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
Curso XML en Tecnologías J2EE
1. El Estándar XML
2. DOM
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
Curso XML en Tecnologías J2EE
Anexo
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
JDOM
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
JDOM
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
JDOM
Ø JDOM, hace uso de menos requerimientos de memoria que el
genérico DOM.
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
JDOM
Ø El API está formado por 5 packages.
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
JDOM
Ø Para construir un objeto Document son JDOM, necesitamos realizarlo
desde un parser de SAX o DOM, para esto empleamos las clases
SAXBuilder o DOMBuilder.
Ejm.:
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
JDOM
Ø a través del objeto Document podemos obtener la raíz del XML,
utilizando el método getRootElement() este método nos retorna un
objeto Element representando la raíz.
Ø Podemos crear elementos de una manera muy simple.
document.addContent(elemento);
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
JDOM
Ø Clase Element
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
JDOM
Ø Clase Element, continua….
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
JDOM
Ø Clase Attribute
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
JDOM
Ø Clase Attribute
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
JDOM
Ø Escribir un XML a Disco
Ø Ejm.:
Ø out.output(document,fw);
Ø fw.close();
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.
JDOM
Ø Ejercicio Practico
Created by PDF Generator (http://www.alientools.com/), to remove this mark, please buy the software.