Está en la página 1de 28

Java y DOM

Alberto Gimeno

Java y DOM por Alberto Gimeno Copyright 2003 por Alberto Gimeno En este tutorial se explica qu es DOM y cmo usarlo desde Java.

Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License".

Historial de revisiones Revisin 1.0 28-09-2003 Revisado por: Alberto Gimeno Documento inicial

Tabla de contenidos
1. Qu es DOM ......................................................................................................................1 DOM es modular..........................................................................................................1 DOM es independiente del lenguaje de programacin..........................................1 DOM es redundante ....................................................................................................1 2. El matrimonio Java y DOM ........................................................................................3 Las interfaces Java ....................................................................................................3 Especicacin versus implementacin .....................................................................3 Una ayuda del API estndar de Java.....................................................................3 Implementaciones DOM .............................................................................................3 Otras APIs similares a DOM.......................................................................................3 3. DOM bsico .......................................................................................................................5 El paquete javax.xml.parsers ................................................................................5 Obteniendo una instancia de DocumentBuilderFactory ............................5 La clase DocumentBuilder ................................................................................5 El paquete org.w3c.dom .............................................................................................7 Manejando excepciones: DOMException .........................................................7 La interfaz DOMImplementation ......................................................................8 El documento: interfaz Document.....................................................................9 La interfaz Node ................................................................................................10 La interfaz Element ..........................................................................................11 Atributos: la interfaz Attr ...............................................................................13 Nodos de texto: interfaz CharacterData .....................................................14 La interfaz DocumentFragment ......................................................................15 Instrucciones de procesamiento .....................................................................15 Tipos de lista......................................................................................................15 El paquete javax.xml.transform ..........................................................................16 A. GNU Free Documentation License ............................................................................19 PREAMBLE .................................................................................................................19 APPLICABILITY AND DEFINITIONS...................................................................19 VERBATIM COPYING ..............................................................................................20 COPYING IN QUANTITY........................................................................................20 MODIFICATIONS......................................................................................................21 COMBINING DOCUMENTS...................................................................................22 COLLECTIONS OF DOCUMENTS.........................................................................23 AGGREGATION WITH INDEPENDENT WORKS..............................................23 TRANSLATION..........................................................................................................23 TERMINATION..........................................................................................................23 FUTURE REVISIONS OF THIS LICENSE..............................................................24 ADDENDUM: How to use this License for your documents .............................24

iii

iv

Captulo 1. Qu es DOM
DOM1 es una especicacin del W3C2. DOM es la especicacin de un API (application programming interface) para documentos HTML y XML especcamente, aunque puede usarse en general para cualquier tipo de documento que guarde informacin jerrquicamente. DOM dene la estructura del documento, la forma de navegar por l y la forma de manipularlo (insertar y eliminar nodos).

DOM es modular
DOM consta de tres niveles. La especicacin DOM nivel 1 dene las interfaces bsicas que modelan un documento en memoria. Dene bsicamente la forma de eliminar e insertar nuevos nodos. La especicacin DOM nivel 2 consta de varios mdulos: Core, Views, Events, Style, Traversal and Range, y HTML. El mdulo Core es una amplicacin de DOM nivel 1 que aade soporte para espacios de nombre XML. El resto de mdulos de DOM nivel 2 se denen a partir del mdulo Core. El mdulo Views dene una forma genrica de asociar una vista a un documento. El mdulo Style es una extensin de Views especca para CSS; dene interfaces para manipular hojas de estilo en cascada relacionadas con un documento. El mdulo Events especica una forma para capturar eventos generados por la modicacin del documento, o eventos generados por una interfaz de usuario. El mdulo Traversal and Range dene interfaces ms avanzadas para recorrer los nodos de un documento y para obtener rangos y colecciones de nodos. Finalmente el mdulo HTML dene interfaces especcas para manejar los tags HTML a ms alto nivel. Existe otro nivel: DOM nivel 3 que todava no es una recomendacin (se denomina recomendacin a los estndares del W3C), est en fase de elavoracin. Contiene mdulos para la persistencia de objetos DOM, XPath, validacin y extensiones de los mdulos de nivel 2. Ms informacin en la pgina de actividad de DOM3 y en la documentacin tcnica4.

DOM es independiente del lenguaje de programacin


El API DOM est diseada para ser usada en cualquier lenguaje de programacin, por ello est especicada usando el lenguaje OMG IDL. Sin embargo, el W3C proporciona tambin deniciones especcas para ECMAScript y Java, es decir, proporciona las mismas interfaces IDL escritas en ECMAScript y Java. No obstante la pgina de DOM del W3C mantiene una lista de implementaciones no ociales en otros lenguajes5. DOM dene dos tipos de datos: DOMString y DOMTimeStamp. Al ser implementado DOM en un lenguaje especco se deben asociar estos tipos de datos a tipos "nativos" del lenguaje de programacin. Particularmente el tipo DOMString se asocia en Java al tipo java.lang.String y el tipo DOMTimeStamp al tipo long. DOM no especica mtodos o funciones para liberar memoria ya que hay lenguajes de programacin, como Java, que poseen recolector de basuras y no requieren liberacin de memoria explcita. La responsabilidad de denir cmo se libera memoria se delega a la implementacin.

DOM es redundante
Debido a que DOM deba ser independiente del lenguaje de programacin, deba poder ser implemnetado tanto en lenguajes ordientados a objetos como en programacin estructurada. Debido a ello la interfaz Node, interfaz base de todos los objetos dentro de un documento, dene mtodos que no tienen sentido para algunas subclases pero s para otras. Por ejemplo no todos los nodos pueden tener nodos hijos (los comentarios no pueden tener hijos), sin embargo todos los nodos tienen mtodos appendChild(), getFirstChild(), etc. Tambin ocurre que hay campos de los objetos que pueden ser obtenidos de diferentes formas. Por ejemplo, el nom1

Captulo 1. Qu es DOM bre de un elemento puede ser obtenido mediante getTagName() o bien mediante getNodeName().

Notas
1. http://www.w3.org/DOM 2. http://www.w3.org 3. http://www.w3.org/DOM/Activity.html 4. http://www.w3.org/DOM/DOMTR 5. http://www.w3.org/DOM/Bindings

Captulo 2. El matrimonio Java y DOM


Las interfaces Java
DOM est especicado en IDL (para cualquier lenguaje de programacin) y tambin hay deniciones especcas para ECMAScript y Java. Por lo tanto todas las especicaciones de los diferentes niveles y mdulos que componen DOM tienen disponible un archivo comprimido con un conjunto de clases e interfaces Java que componen el paquete org.w3c.dom.

Especicacin versus implementacin


Una especicacin es un conjunto de interfaces que denen el comportamiento de una API. Una implementacin es un conjunto de clases que implementan las interfaces de la especicacin. Cuando usemos DOM haremos referencia a las interfaces DOM y no a las clases que las implementan; de esta forma nuestra aplicacin ser independiente de la implementacin: no sufrir acoplamiento con ninguna implementacin especca. Podremos cambiar de implemnetacin sin tocar el cdigo siempre que nos ciamos a la especicacin DOM y siempre que sepamos indicar correctamente la implementacin que queremos usar.

Una ayuda del API estndar de Java


El paquete javax.xml.parsers del API estndar de Java proporciona un par de clases abstractas que toda implementacin DOM para Java debe extender. Estas clases permiten instanciar la implementacin de forma independiente de ella y adicionalmente ofrecen mtodos para cargar documentos desde una fuente de datos (archivo, InputStream, etc.). Este paquete aprovecha algunas clases del API SAX como se ver ms adelante.

Implementaciones DOM
Existen diversas implementaciones de DOM. El JRE viene con una implementacin por defecto. La implementacin libre ms importante de DOM es Xerces1.

Otras APIs similares a DOM


Debido a que DOM est denido para cualquier lenguaje de programacin no aprovecha las caractersticas o APIs del lenguaje de programacin en que est implementada. Por ello han surgido algunos proyectos para crear APIs especcas para Java que aprovechan por ejemplo el API Collections de Java y aprovechan mejor la orientacin a objetos. Estos proyectos poseen APIs ms claras e intuitivas, no redundantes. Los proyectos ms populares son jdom2 y dom4j3. Este ltimo permite interactuar con documentos W3C DOM. En la pgina de dom4j puedes encontrar una comparativa de estas APIs4.

Notas
1. http://xml.apache.org/xerces-j/ 2. http://www.jdom.org 3. http://www.dom4j.org 4. http://www.dom4j.org/compare.html 3

Captulo 2. El matrimonio Java y DOM

Captulo 3. DOM bsico


A partir de ahora es muy conveniente tener a mano la documentacin de Java ya que no voy a copiar en este tutorial todos los mtodos que existen. Por lo tanto es tarea del lector investigar un poco entre la documentacin cuando necesite alguna funcionalidad que no est presente en el tutorial.

El paquete javax.xml.parsers
Este paquete es el punto de partida para usar DOM en Java. Contiene dos clases fundamentales: DocumentBuilderFactory y DocumentBuilder.

Obteniendo una instancia de DocumentBuilderFactory


La clase DocumentBuilderFactory posee un mtodo esttico que permite obtener una implementacin de la clase DocumentBuilderFactory.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

El mtodo newInstance() localizar la clase que implementa DocumentBuilderFactory siguiendo diferentes estrategias: (esta informacin est sacada de la documentacin de Java de este mtodo)

Usando la propiedad del sistema javax.xml.parsers.DocumentBuilderFactory. Esta propiedad del sistema debera contener el nombre de la clase implementacin. Buscando la propiedad javax.xml.parsers.DocumentBuilderFactory en el archivo lib/jaxp.properties del JRE. Usando el API de servicios de Java. Buscando un archivo
META-INF/services/javax.xml.parsers.DocumentBuilderFactory dentro un

archivo JAR.

Finalmente, si ninguno de los intentos anteriores tiene xito se cargar una instancia por defecto

La clase DocumentBuilder
Estableciendo el comportamiento La factora DocumentBuilderFactory nos permite crear parsers con caractersticas de comportamiento determinadas. Estos comportamientos son: validacin, soporte para espacios de nombres, etc. Podemos obtener informacin sobre estos comportamientos a travs de mtodos isXXX() y podemos establecerlos a travs de mtodos setXXX(). Estableciendo estas propiedades la factora nos devolver posteriormente objetos DocumentBuilder que posean un parser subyacente con los comportamientos deseados; si la factora no es capaz de crear objetos con dichos comportamientos se lanzar una excepcin del tipo javax.xml.parsers.ParserConfigurationException. Obtener una instancia de DocumentBuilder es bien sencillo. Basta invocar el mtodo newDocumentBuilder().
import javax.xml.parsers.*; public class Ejemplo1 { public static void main(String args[]){ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //Posibles comportamientos que se pueden establecer:

Captulo 3. DOM bsico

//comprueba si la factoria esta configurada para producir parsers //que validen el documento System.out.println("isValidating: \t\t\t"+ factory.isValidating()); //comprueba si los parsers producidos soportaran espacios de nombres System.out.println("isNamespaceAware: \t\t"+ factory.isNamespaceAware()); //comprueba si los parsers producidos por la factoria //convertiran bloques CDATA a nodos Text System.out.println("isCoalescing: \t\t\t"+ factory.isCoalescing()); //comprueba si los parsers producidos expandiran las entidades System.out.println("isExpandEntityReferences: \t"+ factory.isExpandEntityReferences()); //comprueba si los parsers producidos ignoraran los comentarios System.out.println("isIgnoringComments: \t\t"+ factory.isIgnoringComments()); //Podemos establecerlos con metodos setXXX() factory.setValidating(false); System.out.println("validacion establecida a false"); factory.setNamespaceAware(true); System.out.println("establecido soporte para espacios de nombres"); //etc. try{ DocumentBuilder documentBuilder = factory.newDocumentBuilder(); System.out.println("Obtenido DocumentBulider con exito"); }catch(javax.xml.parsers.ParserConfigurationException e){ System.err.println("No se ha podido crear una instancia de DocumentBuilder"); } } }

Creando documentos Crear un nuevo documento es algo trivial. Basta con invocar al mtodo newDocument() de DocumentBuilder.
org.w3c.dom.Document document = documentBuilder.newDocument();

As obtendremos un documento vaco. Un documento vaco no es un documento bien formado ya que un documento debe contener al menos un, y no ms de un, elemento raz. Ms adelante veremos una forma ms adecuada para crear documentos a travs de la interfaz org.w3c.dom.DOMImplementation. Esta interfaz nos permitir crear documentos con un elemento raz y opcionalmente con un DTD asociado.

Cargando documentos Cargar un documento tambin es algo muy sencillo. Podemos cargar un documento desde un archivo, indicando una URI, o a travs de un InputStream. Tambin podemos usar la clase org.xml.sax.InputSource que encapsula cualquier fuente de datos. Como se puede observar se han aprovechado algunas clases del API SAX como InputSource y SAXException para crear documentos DOM. Vamos a ver un ejemplo de cmo cargar un documento DOM de un archivo: 6

Captulo 3. DOM bsico


import import import import import org.w3c.dom.*; org.xml.sax.SAXException; javax.xml.parsers.*; java.io.File; java.io.IOException;

public class Ejemplo2 { public static void main(String args[]){ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try{ DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(new File("archivo.html")); System.out.println("Documento cargado con exito"); }catch(ParserConfigurationException e){ System.err.println("No se ha podido crear una instancia de DocumentBuilder"); }catch(SAXException e){ System.err.println("Error SAX al parsear el archivo"); }catch(IOException e){ System.err.println("Se ha producido un error de entrada salida"); } } }

El mtodo parse() es un mtodo sobrecargado y acepta un java.io.File, un String conteniendo una URI, un java.io.InputStream o un org.xml.sax.InputSource. DocumentBuilder tambin permite especicar un manejador de errores
org.xml.sax.ErrorHandler o un org.xml.sax.EntityResolver para el parser

subyacente. Como se puede apreciar este paquete est diseado para que el API DOM se implemente sobre un parser SAX. Por ello es normal que usemos algunas clases del API SAX. Con esto hemos terminado con lo bsico del paquete javax.xml.parsers. Bsicamente estos son los pasos que se han de seguir:

Obtener una instancia de DocumentBuilderFactory Indicar a la factora el comportamiento que se desea tenga el parser Obtener un DocumentBuilder que internamente usar un parser con el comportamiento deseado Cargar o crear documentos a travs del DocumentBuilder

El paquete org.w3c.dom
Por supuesto, este es el paquete fundamenal de DOM. Este paquete contiene otros paquetes, cada uno contiene un mdulo. As, pues, el mdulo CSS est contenido en el paquete org.w3c.dom.css. El JSDK viene con las interfaces bsicas de DOM (mdulo Core de DOM nivel 2), es decir contiene el paquete org.w3c.dom sin ningn otro paquete anidado.

Manejando excepciones: DOMException


DOMException es la nica excepcin denida en DOM. Una excepcin DOMException es lanzada cuando una operacin es imposible de llevar a cabo. Una excepcin DOMException tiene un nmero y una cadena de caracteres que identican el tipo

Captulo 3. DOM bsico de excepcin. Los cdigos de tipos de excepciones estn denidos como variables estticas de esta mismca clase.

La interfaz DOMImplementation
La interfaz DOMImplementation nos permite preguntar qu mdulos estn soportados por la implementacin. Esto se consigue mediante el mtodo hasFeature() que requiere dos objetos String como parmetros. El primer parametro es el nombre del mdulo y el segundo es la versin del mdulo. Para todos los mdulos de DOM nivel 2, la versin es 2.0. Si como segundo argumento se pasa una cedena vaca o null se interpreta que estamos preguntando si soporta una versin cualquiera del mdulo.
import org.w3c.dom.*; import javax.xml.parsers.*; public class Ejemplo3 { public static void main(String args[]){ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try{ DocumentBuilder builder = factory.newDocumentBuilder(); DOMImplementation implementation = builder.getDOMImplementation(); System.out.println("Modulos soportados:"); System.out.println("Core: \t\t"+ implementation.hasFeature("Core", "2.0")); System.out.println("XML: \t\t"+ implementation.hasFeature("XML", "2.0")); System.out.println("HTML: \t\t"+ implementation.hasFeature("HTML", "2.0")); System.out.println("Views: \t\t"+ implementation.hasFeature("Views", "2.0")); System.out.println("StyleSheets: \t"+ implementation.hasFeature("StyleSheets", "2.0")); System.out.println("CSS: \t\t"+ implementation.hasFeature("CSS", "2.0")); System.out.println("CSS2: \t\t"+ implementation.hasFeature("CSS2", "2.0")); System.out.println("Events: \t"+ implementation.hasFeature("Events", "2.0")); System.out.println("UIEvents: \t"+ implementation.hasFeature("UIEvents", "2.0")); System.out.println("MouseEvents: \t"+ implementation.hasFeature("MouseEvents", "2.0")); System.out.println("MutationEvents: "+ implementation.hasFeature("MutationEvents", "2.0")); System.out.println("HTMLEvents: \t"+ implementation.hasFeature("HTMLEvents", "2.0")); System.out.println("Range: \t\t"+ implementation.hasFeature("Range", "2.0")); System.out.println("Traversal: \t"+ implementation.hasFeature("Traversal", "2.0")); }catch(ParserConfigurationException e){ System.err.println("No se ha podido crear una instancia de DocumentBuilder"); } } }

Captulo 3. DOM bsico Esta interfaz adems nos permite crear objetos DocumentType y objetos Document bien formados: documentos con un nodo raz y opcionalmente con un DTD (DocumentType).
import org.w3c.dom.*; import javax.xml.parsers.*; public class Ejemplo4 { public static void main(String args[]){ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try{ DocumentBuilder builder = factory.newDocumentBuilder(); DOMImplementation implementation = builder.getDOMImplementation(); DocumentType docType = implementation.createDocumentType("html", "-//W3C//DTD XHTML 1.0 Strict//EN", "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"); Document document = implementation.createDocument("http://www.w3c.org/1999/xhtml", "html", docType); }catch(ParserConfigurationException e){ System.err.println("No se ha podido crear una instancia de DocumentBuilder"); } } }

El documento: interfaz Document


Este es el objeto principal. Sirve como factora para crear nuevos nodos: posee varios mtodos del tipo createXXX() que devuelven nodos de tipos especcos. Los nuevos nodos slo se pueden aadir al documento que los cre, si se intenta aadir un nodo creado por un documento a otro documento se lanza una excepcin del tipo DOMException.WRONG_DOCUMENT_ERR. Un documento slo puede tener un elemento hijo que es el elemento raz del documento. Un documento tambin puede tener asociado o no un objeto DocumentType y varios hijos ProcessingInstruction. De esta forma se obtiene el elemento raz del documento:
Element root = document.getDocumentElement();

El objeto DocumentType nos permite obtener informacin sobre el tipo de documento (DTD). A travs de este objeto podemos acceder a las Entities y Notations. De la siguiente forma se obtiene el DocumentType de un documento:
DocumentType docType = document.getDoctype();

El objeto Document permite obtener listados de elementos por tagName y/o por espacio de nombres y tambin podemos buscar un elemento por su identicador. Los listados de elementos se devuelven en forma de NodeList. NodeList es una interfaz que slo dene dos mtodos: getLength() que devuelve la longitud de la lista e item(int index) que devuelve un Node de la lista por su ndice. Las APIs como jdom o dom4j usan una java.util.Collection que puede ser recorrida mediante un java.util.Iterator; esta es una mejora sustancial frente a los NodeList de DOM. Ms adelante se vern los tipos de lista denidos por DOM.
import org.w3c.dom.*; import org.xml.sax.SAXException;

Captulo 3. DOM bsico


import javax.xml.parsers.*; import java.io.File; import java.io.IOException; public class Ejemplo5 { public static void main(String args[]){ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try{ DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(new File("archivo.html")); NodeList imagenes = document.getElementsByTagName("img"); for(int i=0; i<imagenes.getLength(); i++){ //obviamente la lista solo contendra elementos Element e = (Element)imagenes.item(i); //hacer algo aqui... //en este caso imprimimos el atributo src System.out.println(e.getAttribute("src")); } }catch(ParserConfigurationException e){ System.err.println("No se ha podido crear una instancia de DocumentBuilder"); }catch(SAXException e){ System.err.println("Error SAX al parsear el archivo"); }catch(IOException e){ System.err.println("Se ha producido un error de entrada salida"); } } }

Un documento es tambin un nodo: la interfaz Document extiende de la interfaz Node que vamos a tratar a continuacin.

La interfaz Node
Esta es la interfaz base ya que todos los objetos de un rbol DOM son nodos. Todos los nodos tienen un campo ownerDocument que referencia al documento que lo contiene, a excepcin de los documentos, cuyo ownerDocument es null. La mayora de los nodos tienen un nodo padre, y todos los nodos tienen un hermano anterior y un hermano siguiente (previousSibling y nextSibling). Para obtener estos objetos llamamos a los mtodos getOwnerDocument(), getParentNode(), getPreviousSibling() y getNextSibling() respectivamente. Estos mtodos permiten recorrer todo el rbol de nodos. Todos los nodos tienen un nombre y un valor. Para obtener estas propiedades usamos getNodeName() y getNodeValue() respectivamente. Realmente la mayora de los nodos devuelven null en getNodeValue() y la mayora de los nodos devuelven un valor constante en getNodeName() tales como #document, #comment, etc. En la documentacin de Java podemos ver la tabla de valores que devolvern los diferentes tipos de nodos. El valor de un nodo se puede modicar a travs del mtodo setNodeValue(String s); este mtodo lanzar una excepcin DOMException.NO_MODIFICATION_ALLOWED_ERR en caso de ser un nodo de slo lectura. Esta misma excepcin puede ser lanzada en cualquier intento de modicar un nodo que sea de slo lectura. No todos los nodos pueden tener hijos, pero, debido a que el diseo del API DOM deba ser vlido para lenguajes no orientados a objetos, la interfaz Node provee mtodos para manipular los nodos hijos de cualquier nodo. Podemos obtener el primer nodo hijo mediante getFirstChild(); podemos obtener el ltimo nodo hijo mediante getLastChild() y podemos obtener una lista (NodeList) de hijos mediante getChildNodes(). Para modicar (insertar y elminiar) los hijos de un 10

Captulo 3. DOM bsico nodotenemos varios mtodos: appendChild(Node newChild) que inserta un nodo al nal de la lista, removeChild(Node oldChild) que elimina el nodo especicado, replaceChild(Node newChild, Node refChild) que sustituye un nodo por otro e insertBefore(Node newChild, Node refChild) que inserta el nodo newChild antes de refChild. Cualquier intento de modicar una lista de hijos de un nodo que no admite nodos hijos provocar que se lance una excepcin DOMException.HIERARCHY_REQUEST_ERR. Ahora que hemos aprendido a manejar bsicamente la interfaz Node veamos un ejemplo de cmo recorrer un rbol DOM usando los mtodos getFirstChild() y getNextSibling().
import import import import import org.w3c.dom.*; org.xml.sax.SAXException; javax.xml.parsers.*; java.io.File; java.io.IOException;

public class Ejemplo6 { public static void print(String s, int level){ for(; level>0; level--) System.out.print("\t"); System.out.println(s); } public static void listChildren(Node e, int level){ print("[ "+e.getNodeName()+" ]", level); level++; for(Node node = e.getFirstChild(); node != null; node = node.getNextSibling()){ listChildren(node, level); } } public static void main(String args[]){ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try{ DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(new File("archivo.html")); listChildren(document, 0); }catch(ParserConfigurationException e){ System.err.println("No se ha podido crear una instancia de DocumentBuilder"); }catch(SAXException e){ System.err.println("Error SAX al parsear el archivo"); System.err.println(e); }catch(IOException e){ System.err.println("Se ha producido un error de entrada salida"); } } }

La interfaz Node tiene ms mtodos que sern explicados en adelante, cuando tengan sentido usarse.

11

Captulo 3. DOM bsico

La interfaz Element
Los elementos son quiz los nodos ms comunes dentro de un rbol DOM, son los tags de XML y HTML. Los elementos tienen atributos y pueden tener nodos hijos. Adems los elementos pueden tener un espacio de nombres asociados y un prejo. Junto a los atributos son los nicos nodos que soportan espacios de nombre. En caso de tener un espacio de nombres asociado el elemento tendr cuatro propiedades: el prejo, el nombre local, la URI del espacio de nombres y el qualifiedName que es prejo+":"+localName. Todos ellos son objetos String. El mtodo getNodeName() devolver el qualifiedName. Para obtener el resto de propiedades existen los mtodos getPrefix(), getNamespaceURI() y getLocalName() introducidos en la interfaz Node. Slo el prejo es modicable mediante el mtodo setPrefix(String prefix). En caso de no tener un espacio de nombres asociado getLocalName(), getNamespaceURI() y getPrefix() devolvern null. Existe un mtodo redundante que devuelve lo mismo que getNodeName() y es getTagName(). Los atributos de un elemento se pueden obtener mediante getAttributes() que devuelve una lista NamedNodeMap. A pesar de que slo los tipos de nodo Element pueden poseer atributos, debido al diseo independiente de lenguajes orientados a objetos, este mtodo es introducido en la interfaz Node. El tipo de lista NamedNodeMap es una lista desordenada en la que los nodos se pueden eliminar a travs de su nombre y opcionalmente tambin por su espacio de nombres. La interfaz NamedNodeMap, al igual que NodeList, tiene un mtodo getLength() y un mtodo item(int index) que permite hacer un recorrido de los nodos que forman parte de la lista. Los tipos de lista se tratarn ms adelante. Vamos a ampliar el ejemplo anterior para que tambin muestre los atributos de cada elemento y el prejo y espacio de nombres asociado (si tiene).
import import import import import org.w3c.dom.*; org.xml.sax.SAXException; javax.xml.parsers.*; java.io.File; java.io.IOException;

public class Ejemplo7 { public static void print(String s, int level){ for(; level>0; level--) System.out.print("\t"); System.out.println(s); } public static void listChildren(Node e, int level){ //si es un elemento con espacio de nombres asociado... if(e instanceof Element && ((Element)e).getLocalName() != null){ Element el = (Element)e; print("[ "+el.getPrefix()+" : "+el.getLocalName()+ " :: "+el.getNamespaceURI()+" ]", level); } else { print("[ "+e.getNodeName()+" ]", level); } level++; //imprimimos los atributos, notese que a pesar de que //la variable e debe ser un Elemento para tener atributos, //no necesitamos hacer un cast porque la interfaz Node //provee los metodos para obtener los atributos if(e.hasAttributes()){ NamedNodeMap attributes = e.getAttributes(); int length = attributes.getLength(); Attr attr = null; for(int i=0; i<length; i++){ attr = (Attr)attributes.item(i);

12

Captulo 3. DOM bsico


print(attr.getNodeName()+"="+attr.getNodeValue()+"", level); } } for(Node node = e.getFirstChild(); node != null; node = node.getNextSibling()){ listChildren(node, level); } } public static void main(String args[]){ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try{ DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(new File("archivo.html")); listChildren(document, 0); }catch(ParserConfigurationException e){ System.err.println("No se ha podido crear una instancia de DocumentBuilder"); }catch(SAXException e){ System.err.println("Error SAX al parsear el archivo"); System.err.println(e); }catch(IOException e){ System.err.println("Se ha producido un error de entrada salida"); } } }

Crear un elemento es muy sencillo. Podemos crear elementos con espacio de nombres asociado o sin l.
Element unelemento = document.createElement(String name); Element otroelemento = document.createElementNS(String namespaceURI, String qualifiedName);

Atributos: la interfaz Attr


Los atributos son un tipo de nodo muy caracterstico. Slo existen dentro de elementos y no forman parte del rbol. Estrictamente no tienen un nodo padre, es decir, getParentNode() devuelve null, y tampoco tienen nodos hermanos (getNextSibling() y getPreviousSibling() devuelven null). Sin embargo s que pueden tener nodos hijo (solamente de los tipos Text y EntityReference, y slo en documentos XML). Junto a los elementos son los nicos nodos que tienen soporte para espacios de nombre. El soporte de espacios de nombre es idntico que en la interfaz Element. Los valores se obtienen y establecen con los mismos mtodos y tienen el mismo comportamiento. Los atributos son de los pocos tipos de nodo que contienen algn valor. Existen dos mtodos redundantes: getName() y getValue() que devuelven lo mismo que getNodeName() y getNodeValue() respectivamente. Un atributo no tiene un nodo padre, sin embargo, s tiene un elemento propietario. Este elemento se puede obtener mediante el mtodo getOwnerElement(). Los atributos pueden haber adquirido su valor explcitamente a travs del mtodo setValue() o setNodeValue(), o pueden tener un valor por defecto denido en el DTD del documento. En caso de tener un valor explcito, el mtodo getSpecified() devolver true, y devolver false en caso contrario. Los atributos se crean de forma casi idntica a los elementos:
Attr unatributo = document.createAttribute(String name);

13

Captulo 3. DOM bsico


Attr otroatributo = document.createAttributeNS(String namespaceURI, String qualifiedName);

Nodos de texto: interfaz CharacterData


La interfaz CharacterData es superinterfaz de las interfaces: Text y Comment. La interfaz Text es a su vez superitnerfaz de CDATASection. Todas estas interfaces representan nodos que contienen texto. Debido a ello tienen mtodos comunes que son denidos en la interfaz CharacterData. Estos mtodos permiten obtener y manipular el texto. Son mtodos muy intuitivos, as que es tarea del lector documentarse con el API de Java.
Text y Comment tienen semnticas muy diferentes. El primero representa el texto

contenido entre elementos, mientras que el segundo representa los comentarios de un documento. La interfaz Comment no aade ningn mtodo adicional. La interfaz Text aade el mtodo splitText(int offset). Este mtodo recorta el texto del objeto Text hasta la posicion offset y devuelve otro objeto con el resto del texto. Esto est pensado para insertar nodos entre el texto.
import org.w3c.dom.*; import javax.xml.parsers.*; public class Ejemplo8 { public static void print(String s, int level){ for(; level>0; level--) System.out.print("\t"); System.out.println(s); } public static void listChildren(Node e, int level){ print("[ "+e.getNodeName()+" , "+e.getNodeValue()+" ]", level); level++; for(Node node = e.getFirstChild(); node != null; node = node.getNextSibling()){ listChildren(node, level); } } public static void main(String args[]){ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = null; try{ builder = factory.newDocumentBuilder(); }catch(ParserConfigurationException e){ System.err.println("No se ha podido crear una instancia de DocumentBuilder"); return; } DOMImplementation implementation = builder.getDOMImplementation(); Document document = implementation.createDocument(null, "root", null); Element rootElement = document.getDocumentElement(); Text text = document.createTextNode("Este es un texto muy largo."+ +" Pero que muy largo"); rootElement.appendChild(text); System.out.println(); System.out.println("Antes de insertar un nodo"); listChildren(document, 0); Element smiley = document.createElement("smiley");

14

Captulo 3. DOM bsico


Text anotherText = text.splitText(27); rootElement.appendChild(smiley); rootElement.appendChild(anotherText); System.out.println(); System.out.println("Despues de insertarlo"); listChildren(document, 0); } }

Ahora unos ejemplos de cmo crear comentarios, nodos de texto y secciones CDATA.
Comment comentario = document.createComment("Esto es un comentario"); Text nodoTexto = document.createTextNode("Esto es texto"); CDATASection cdata = document.createCDATASection("Esto es un bloque CDATA");

La interfaz DocumentFragment
Un objeto DocumentFragment es similar a un objeto Document, con la salvedad de que no necesita estar bien formado: no tiene limitaciones en sus nodos hijos y no posee un objeto DocumentType asociado. La interfaz DocumentFragment est pensada para manejar ramas del rbol DOM. Se puede pensar en un objeto DocumentFragment como si fuera un simple contenedor de nodos. Estos nodos, y sus respectivos nodos hijos, forman una rama del rbol DOM. Los mtodos de insercin de nodos (appendChild(), insertBefore(), etc.) tienen comportamientos diferentes si el nodo que se les pasa para insertar es un nodo DocumentFragment. En caso de ser un nodo DocumentFragment lo que se va insertar, se insertarn sus nodos hijos y no simplemente el nodo DocumentFragment. Un objeto DocumentFragment no puede formar parte de un rbol DOM, simplemente sirve para transportar ramas de un rbol DOM. Crear un objeto DocumentFragment es sencillo:
DocumentFragment rama = document.createDocumentFragment();

Instrucciones de procesamiento
La interfaz ProcessingInstruction es muy simple; representa una instruccin de procesamiento. Slo contine dos propiedades: target y data; que pueden ser obtenidas mediante getTarget() y getData() respectivamente. La propiedad target no puede ser modicada, pero la propiedad data s puede, a travs del mtodo setData(String data). La propiedad target representa la palabra que se sita inmediatamente despus de <? y la propiedad data contiene el resto de informacin de la instruccin de procesamiento. Crear una instruccin de procesamiento es algo muy sencillo. A continuacin un ejemplo:
ProcessingInstruction pi = document.createProcessingInstruction( "xml-stylesheet", "type=text/xsl href=stylesheet.xml");

15

Captulo 3. DOM bsico

Tipos de lista
Los nodos que forman parte de los dos tipos de lista DOM (NodeList y NamedNodeMap) estn "vivos"; quiere decir que, por ejemplo, los cambios realizados en los hijos de un elemento se reejan automticamente en su lista de hijos aunque la lista haya sido obtenida antes de que se produjera el cambio. A continuacin el ejemplo del apartado anterior modicado para que muestre el numero de nodos hijos del nodo raz del documento.
import org.w3c.dom.*; import javax.xml.parsers.*; public class Ejemplo9 { public static void main(String args[]){ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = null; try{ builder = factory.newDocumentBuilder(); }catch(ParserConfigurationException e){ System.err.println("No se ha podido crear una instancia de DocumentBuilder"); return; } DOMImplementation implementation = builder.getDOMImplementation(); Document document = implementation.createDocument(null, "root", null); Element rootElement = document.getDocumentElement(); Text text = document.createTextNode("Este es un texto muy largo."+ " Pero que muy largo"); rootElement.appendChild(text); NodeList children = rootElement.getChildNodes(); System.out.println("Antes de insertar"); System.out.println("numero hijos: "+children.getLength()); Element smiley = document.createElement("smiley"); Text anotherText = text.splitText(27); rootElement.appendChild(smiley); rootElement.appendChild(anotherText); System.out.println(); System.out.println("Despues de insertar"); System.out.println("numero hijos: "+children.getLength()); } }

El tipo de lista NodeList representa una lista ordenada de nodos. Adecuada por ejemplo para obtener los nodos hijos de otro nodo. Este tipo de lista es muy simple, slo contiene dos mtodos que simplemente sirven para recorrer todos los nodos que la componen. Anteriormente ya se ha visto algn ejemplo de utilizacin. El tipo de lista NamedNodeMap es ms complejo. Representa una lista desordenada: en la que no importa el orden de los nodos. Por lo tanto es adecuada para, por ejemplo, almacenar los atributos de un elemento. En este tipo de lista los nodos se pueden recorrer del mismo modo que en una lista NodeList. Los nodos pueden tambin ser obtenidos a partir de su nombre y opcionalmente a partir de su espacio de nombres. Esta lista es modicable; se pueden eliminar nodos e insertarlos. Ms informacin en el API estndar de Java.

16

Captulo 3. DOM bsico

El paquete javax.xml.transform
DOM no dene ningn mecanismo para generar un chero XML a partir de un rbol DOM. De modo que aqu voy a presentar un truco para realizar esta tarea. No me voy a detener mucho en el tema. Es tarea del lector ampliar conocimientos con el API Java. Quiz en posteriores revisiones del tutorial ofrezca ms informacin sobre este paquete. El paquete javax.xml.transform est diseado para realizar modicaciones a documentos. Es usado mayoritariamente para manejar plantillas XLST. Permite especicar una fuente y un resultado. La fuente y el resultado pueden ser archivos, ujos de datos o nodos DOM entre otros. Nuestro truco consiste en crear una plantilla que no haga ninguna transformacin y especicaremos como fuente un documento DOM y como destino un archivo. Adicionalmente mostraremos el documento por pantalla especicando como resultado el canal de salida (System.out).
import import import import import org.w3c.dom.*; javax.xml.parsers.*; javax.xml.transform.*; javax.xml.transform.dom.*; javax.xml.transform.stream.*;

public class Ejemplo10 { public static void main(String args[]){ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try{ DocumentBuilder builder = factory.newDocumentBuilder(); DOMImplementation implementation = builder.getDOMImplementation(); Document document = implementation.createDocument(null, "html", null); Element body = document.createElement("body"); Element para = document.createElement("p"); Text text = document.createTextNode("Esto es un parrafo"); document.getDocumentElement().appendChild(body); body.appendChild(para); para.appendChild(text); Source source = new DOMSource(document); Result result = new StreamResult(new java.io.File("resultado.xml")); Result console= new StreamResult(System.out); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.transform(source, result); transformer.transform(source, console); }catch(Exception e){ System.err.println("Error: "+e); } } }

17

Captulo 3. DOM bsico

18

Apndice A. GNU Free Documentation License


Copyright (C) 2000,2001,2002 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.

PREAMBLE
The purpose of this License is to make a manual, textbook, or other functional and useful document "free" in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it, with or without modifying it, either commercially or noncommercially. Secondarily, this License preserves for the author and publisher a way to get credit for their work, while not being considered responsible for modications made by others. This License is a kind of "copyleft", which means that derivative works of the document must themselves be free in the same sense. It complements the GNU General Public License, which is a copyleft license designed for free software. We have designed this License in order to use it for manuals for free software, because free software needs free documentation: a free program should come with manuals providing the same freedoms that the software does. But this License is not limited to software manuals; it can be used for any textual work, regardless of subject matter or whether it is published as a printed book. We recommend this License principally for works whose purpose is instruction or reference.

APPLICABILITY AND DEFINITIONS


This License applies to any manual or other work, in any medium, that contains a notice placed by the copyright holder saying it can be distributed under the terms of this License. Such a notice grants a world-wide, royalty-free license, unlimited in duration, to use that work under the conditions stated herein. The "Document", below, refers to any such manual or work. Any member of the public is a licensee, and is addressed as "you". You accept the license if you copy, modify or distribute the work in a way requiring permission under copyright law. A "Modied Version" of the Document means any work containing the Document or a portion of it, either copied verbatim, or with modications and/or translated into another language. A "Secondary Section" is a named appendix or a front-matter section of the Document that deals exclusively with the relationship of the publishers or authors of the Document to the Documents overall subject (or to related matters) and contains nothing that could fall directly within that overall subject. (Thus, if the Document is in part a textbook of mathematics, a Secondary Section may not explain any mathematics.) The relationship could be a matter of historical connection with the subject or with related matters, or of legal, commercial, philosophical, ethical or political position regarding them. The "Invariant Sections" are certain Secondary Sections whose titles are designated, as being those of Invariant Sections, in the notice that says that the Document is released under this License. If a section does not t the above denition of Secondary then it is not allowed to be designated as Invariant. The Document may contain zero Invariant Sections. If the Document does not identify any Invariant Sections then there are none. The "Cover Texts" are certain short passages of text that are listed, as Front-Cover Texts or Back-Cover Texts, in the notice that says that the Document is released under

19

Apndice A. GNU Free Documentation License this License. A Front-Cover Text may be at most 5 words, and a Back-Cover Text may be at most 25 words. A "Transparent" copy of the Document means a machine-readable copy, represented in a format whose specication is available to the general public, that is suitable for revising the document straightforwardly with generic text editors or (for images composed of pixels) generic paint programs or (for drawings) some widely available drawing editor, and that is suitable for input to text formatters or for automatic translation to a variety of formats suitable for input to text formatters. A copy made in an otherwise Transparent le format whose markup, or absence of markup, has been arranged to thwart or discourage subsequent modication by readers is not Transparent. An image format is not Transparent if used for any substantial amount of text. A copy that is not "Transparent" is called "Opaque". Examples of suitable formats for Transparent copies include plain ASCII without markup, Texinfo input format, LaTeX input format, SGML or XML using a publicly available DTD, and standard-conforming simple HTML, PostScript or PDF designed for human modication. Examples of transparent image formats include PNG, XCF and JPG. Opaque formats include proprietary formats that can be read and edited only by proprietary word processors, SGML or XML for which the DTD and/or processing tools are not generally available, and the machine-generated HTML, PostScript or PDF produced by some word processors for output purposes only. The "Title Page" means, for a printed book, the title page itself, plus such following pages as are needed to hold, legibly, the material this License requires to appear in the title page. For works in formats which do not have any title page as such, "Title Page" means the text near the most prominent appearance of the works title, preceding the beginning of the body of the text. A section "Entitled XYZ" means a named subunit of the Document whose title either is precisely XYZ or contains XYZ in parentheses following text that translates XYZ in another language. (Here XYZ stands for a specic section name mentioned below, such as "Acknowledgements", "Dedications", "Endorsements", or "History".) To "Preserve the Title" of such a section when you modify the Document means that it remains a section "Entitled XYZ" according to this denition. The Document may include Warranty Disclaimers next to the notice which states that this License applies to the Document. These Warranty Disclaimers are considered to be included by reference in this License, but only as regards disclaiming warranties: any other implication that these Warranty Disclaimers may have is void and has no effect on the meaning of this License.

VERBATIM COPYING
You may copy and distribute the Document in any medium, either commercially or noncommercially, provided that this License, the copyright notices, and the license notice saying this License applies to the Document are reproduced in all copies, and that you add no other conditions whatsoever to those of this License. You may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute. However, you may accept compensation in exchange for copies. If you distribute a large enough number of copies you must also follow the conditions in section 3. You may also lend copies, under the same conditions stated above, and you may publicly display copies.

COPYING IN QUANTITY
If you publish printed copies (or copies in media that commonly have printed covers) of the Document, numbering more than 100, and the Documents license notice 20

Apndice A. GNU Free Documentation License requires Cover Texts, you must enclose the copies in covers that carry, clearly and legibly, all these Cover Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on the back cover. Both covers must also clearly and legibly identify you as the publisher of these copies. The front cover must present the full title with all words of the title equally prominent and visible. You may add other material on the covers in addition. Copying with changes limited to the covers, as long as they preserve the title of the Document and satisfy these conditions, can be treated as verbatim copying in other respects. If the required texts for either cover are too voluminous to t legibly, you should put the rst ones listed (as many as t reasonably) on the actual cover, and continue the rest onto adjacent pages. If you publish or distribute Opaque copies of the Document numbering more than 100, you must either include a machine-readable Transparent copy along with each Opaque copy, or state in or with each Opaque copy a computer-network location from which the general network-using public has access to download using publicstandard network protocols a complete Transparent copy of the Document, free of added material. If you use the latter option, you must take reasonably prudent steps, when you begin distribution of Opaque copies in quantity, to ensure that this Transparent copy will remain thus accessible at the stated location until at least one year after the last time you distribute an Opaque copy (directly or through your agents or retailers) of that edition to the public. It is requested, but not required, that you contact the authors of the Document well before redistributing any large number of copies, to give them a chance to provide you with an updated version of the Document.

MODIFICATIONS
You may copy and distribute a Modied Version of the Document under the conditions of sections 2 and 3 above, provided that you release the Modied Version under precisely this License, with the Modied Version lling the role of the Document, thus licensing distribution and modication of the Modied Version to whoever possesses a copy of it. In addition, you must do these things in the Modied Version: A. Use in the Title Page (and on the covers, if any) a title distinct from that of the Document, and from those of previous versions (which should, if there were any, be listed in the History section of the Document). You may use the same title as a previous version if the original publisher of that version gives permission. B. List on the Title Page, as authors, one or more persons or entities responsible for authorship of the modications in the Modied Version, together with at least ve of the principal authors of the Document (all of its principal authors, if it has fewer than ve), unless they release you from this requirement. C. State on the Title page the name of the publisher of the Modied Version, as the publisher. D. Preserve all the copyright notices of the Document. E. Add an appropriate copyright notice for your modications adjacent to the other copyright notices. F. Include, immediately after the copyright notices, a license notice giving the public permission to use the Modied Version under the terms of this License, in the form shown in the Addendum below. G. Preserve in that license notice the full lists of Invariant Sections and required Cover Texts given in the Documents license notice. H. Include an unaltered copy of this License. 21

Apndice A. GNU Free Documentation License I. Preserve the section Entitled "History", Preserve its Title, and add to it an item stating at least the title, year, new authors, and publisher of the Modied Version as given on the Title Page. If there is no section Entitled "History" in the Document, create one stating the title, year, authors, and publisher of the Document as given on its Title Page, then add an item describing the Modied Version as stated in the previous sentence. J. Preserve the network location, if any, given in the Document for public access to a Transparent copy of the Document, and likewise the network locations given in the Document for previous versions it was based on. These may be placed in the "History" section. You may omit a network location for a work that was published at least four years before the Document itself, or if the original publisher of the version it refers to gives permission. K. For any section Entitled "Acknowledgements" or "Dedications", Preserve the Title of the section, and preserve in the section all the substance and tone of each of the contributor acknowledgements and/or dedications given therein. L. Preserve all the Invariant Sections of the Document, unaltered in their text and in their titles. Section numbers or the equivalent are not considered part of the section titles. M. Delete any section Entitled "Endorsements". Such a section may not be included in the Modied Version. N. Do not retitle any existing section to be Entitled "Endorsements" or to conict in title with any Invariant Section. O. Preserve any Warranty Disclaimers. If the Modied Version includes new front-matter sections or appendices that qualify as Secondary Sections and contain no material copied from the Document, you may at your option designate some or all of these sections as invariant. To do this, add their titles to the list of Invariant Sections in the Modied Versions license notice. These titles must be distinct from any other section titles. You may add a section Entitled "Endorsements", provided it contains nothing but endorsements of your Modied Version by various parties--for example, statements of peer review or that the text has been approved by an organization as the authoritative denition of a standard. You may add a passage of up to ve words as a Front-Cover Text, and a passage of up to 25 words as a Back-Cover Text, to the end of the list of Cover Texts in the Modied Version. Only one passage of Front-Cover Text and one of Back-Cover Text may be added by (or through arrangements made by) any one entity. If the Document already includes a cover text for the same cover, previously added by you or by arrangement made by the same entity you are acting on behalf of, you may not add another; but you may replace the old one, on explicit permission from the previous publisher that added the old one. The author(s) and publisher(s) of the Document do not by this License give permission to use their names for publicity for or to assert or imply endorsement of any Modied Version.

COMBINING DOCUMENTS
You may combine the Document with other documents released under this License, under the terms dened in section 4 above for modied versions, provided that you include in the combination all of the Invariant Sections of all of the original documents, unmodied, and list them all as Invariant Sections of your combined work in its license notice, and that you preserve all their Warranty Disclaimers. The combined work need only contain one copy of this License, and multiple identical Invariant Sections may be replaced with a single copy. If there are multiple Invari22

Apndice A. GNU Free Documentation License ant Sections with the same name but different contents, make the title of each such section unique by adding at the end of it, in parentheses, the name of the original author or publisher of that section if known, or else a unique number. Make the same adjustment to the section titles in the list of Invariant Sections in the license notice of the combined work. In the combination, you must combine any sections Entitled "History" in the various original documents, forming one section Entitled "History"; likewise combine any sections Entitled "Acknowledgements", and any sections Entitled "Dedications". You must delete all sections Entitled "Endorsements".

COLLECTIONS OF DOCUMENTS
You may make a collection consisting of the Document and other documents released under this License, and replace the individual copies of this License in the various documents with a single copy that is included in the collection, provided that you follow the rules of this License for verbatim copying of each of the documents in all other respects. You may extract a single document from such a collection, and distribute it individually under this License, provided you insert a copy of this License into the extracted document, and follow this License in all other respects regarding verbatim copying of that document.

AGGREGATION WITH INDEPENDENT WORKS


A compilation of the Document or its derivatives with other separate and independent documents or works, in or on a volume of a storage or distribution medium, is called an "aggregate" if the copyright resulting from the compilation is not used to limit the legal rights of the compilations users beyond what the individual works permit. When the Document is included in an aggregate, this License does not apply to the other works in the aggregate which are not themselves derivative works of the Document. If the Cover Text requirement of section 3 is applicable to these copies of the Document, then if the Document is less than one half of the entire aggregate, the Documents Cover Texts may be placed on covers that bracket the Document within the aggregate, or the electronic equivalent of covers if the Document is in electronic form. Otherwise they must appear on printed covers that bracket the whole aggregate.

TRANSLATION
Translation is considered a kind of modication, so you may distribute translations of the Document under the terms of section 4. Replacing Invariant Sections with translations requires special permission from their copyright holders, but you may include translations of some or all Invariant Sections in addition to the original versions of these Invariant Sections. You may include a translation of this License, and all the license notices in the Document, and any Warranty Disclaimers, provided that you also include the original English version of this License and the original versions of those notices and disclaimers. In case of a disagreement between the translation and the original version of this License or a notice or disclaimer, the original version will prevail. If a section in the Document is Entitled "Acknowledgements", "Dedications", or "History", the requirement (section 4) to Preserve its Title (section 1) will typically require changing the actual title.

23

Apndice A. GNU Free Documentation License

TERMINATION
You may not copy, modify, sublicense, or distribute the Document except as expressly provided for under this License. Any other attempt to copy, modify, sublicense or distribute the Document is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.

FUTURE REVISIONS OF THIS LICENSE


The Free Software Foundation may publish new, revised versions of the GNU Free Documentation License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. See http://www.gnu.org/copyleft/. Each version of the License is given a distinguishing version number. If the Document species that a particular numbered version of this License "or any later version" applies to it, you have the option of following the terms and conditions either of that specied version or of any later version that has been published (not as a draft) by the Free Software Foundation. If the Document does not specify a version number of this License, you may choose any version ever published (not as a draft) by the Free Software Foundation.

ADDENDUM: How to use this License for your documents


To use this License in a document you have written, include a copy of the License in the document and put the following copyright and license notices just after the title page:
Copyright (c) YEAR YOUR NAME. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License".

If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts, replace the "with...Texts." line with this:
with the Invariant Sections being LIST THEIR TITLES, with the Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST.

If you have Invariant Sections without Cover Texts, or some other combination of the three, merge those two alternatives to suit the situation. If your document contains nontrivial examples of program code, we recommend releasing these examples in parallel under your choice of free software license, such as the GNU General Public License, to permit their use in free software.

24

También podría gustarte