Acceso a ficheros XML con SAX

SAX

·         API Simple para XML, orientada a eventos. Define una serie de interfaces cuyos métodos son controladores de evento.

·         Es un procesador de documentos XML o parser (nos permite leer el contenido de ficheros XML así como acceder a su estructura). Cuando se analiza un documento, el procesador (parse) notifica a los controladores de evento (métodos) los distintos eventos que van teniendo lugar (principio de documento (startDocument), etiqueta de apertura (startElement), etiqueta de cierre (endElement), contenido de elemento (characters) …., fin de documento (endDocument))

·         Es independiente del lenguaje de programación. Existen versiones para Java, VisualBasic, C…

·         Lee el fichero XML de manera secuencial y produce una secuencia de eventos (comienzo/fin de documento, comienzo/fin de etiqueta…) en función de lo que va leyendo. Cada evento invoca un método definido por el programador. Este procesamiento consume muy poca memoria pero impide tener una visión global del documento XML.

 

Como hemos dicho antes, SAX nos proporciona una serie de eventos y nosotros deberemos de decidir qué tarea realizar cuando se produzca cada uno de ellos. Para ello, el conjunto de eventos posibles a manejar se deberán de agrupar en lo que SAX denomina Handler o Manejador. La clase que tiene los eventos por defecto es DefaultHandler. Asi que crearemos un “manejador” que herede de DefaultHandler, en el cual implementaremos la funcionalidad que nos interese para cada uno de los eventos que queramos.

public class MiManejador extends DefaultHandler {}

Métodos de la clase DefaultHandler (a redefinir. Tienen implementaciones vacías)

 void

startDocument() throws SAXException


          Receive notification of the beginning of the document.

 void

startElement(java.lang.String uri, java.lang.String localName, java.lang.String qName, Attributes attributes) throws SAXException


          Receive notification of the start of an element.

uri - The Namespace URI, or the empty string if the element has no Namespace URI or if Namespace processing is not being performed.

localName - The local name (without prefix), or the empty string if Namespace processing is not being performed.

qName - The qualified name (with prefix), or the empty string if qualified names are not available.

attributes - The attributes attached to the element. If there are no attributes, it shall be an empty Attributes object.

 

Interface Attributes. Nos permite accede a los atributos de un element.

int getLength() 
          Return the number of attributes in the list.

java.lang.String getLocalName(int index) 
          Look up an attribute's local name by index.

 void

characters(char[] ch, int start, int length) throws SAXException

 

          Receive notification of character data inside an element.

ch - The characters.

start - The start position in the character array.

length - The number of characters to use from the character array.

 void

endElement(java.lang.String uri, java.lang.String localName, java.lang.String qName) throws SAXException


          Receive notification of the end of an element.

uri - The Namespace URI, or the empty string if the element has no Namespace URI or if Namespace processing is not being performed.

localName - The local name (without prefix), or the empty string if Namespace processing is not being performed.

qName - The qualified name (with prefix), or the empty string if qualified names are not available.

 void

endDocument() throws SAXException


          Receive notification of the end of the document.

 

Una vez que hemos creado el manejador, deberemos realizar la aplicación que utilice dicho manejador para analizar el documento.

Lo primero que necesitamos es crear un objeto procesador de XML, es decir, un XMLReader, durante la creación de este objeto se puede producir una excepción SAXException que es necesario capturar.

XMLReader miprocesadorSAX = XMLReaderFactory.createXMLReader();

Posteriormente tendremos que asociar el manejador definido con el procesador XML para seguidamente procesar el documento. A continuación se indican los métodos necesarios para realizar estar tareas.

Métodos de la interface XMLReader

 void

setContentHandler(ContentHandler handler) 
          
 Asocia un manejador a un procesador XML.

 void

parse(InputSource input) 
          Procesa un documento XML.

 

Comentarios

Entradas populares de este blog

Ficheros (4/5). Flujos de bytes. Ejercicio 9

Ficheros (3/?). Flujos de caracteres. FileWriter, BufferedWrite, PrintWriter