LECTURA XML DESDE JAVA

En el siguiente ejemplo se hace un recorrido por un fichero XML de nombre "empleados.xml" que contiene una lista con la siguiente estructura de empleados con algunos de sus datos:
<?xml version="1.0" encoding="UTF-8"?>
<EMPLEADOS>
   <EMPLEADO>
     <NOMBRE>LUIS MIGUEL</NOMBRE>
     <APELLIDOS>GALLARDO LEON</APELLIDOS>
     <NIF>5674179P</NIF>
     <EMPRESA>DATATONIC, S.A.</EMPRESA>
     <DIRECCION>HERMANOS ARAGON , CALLE</DIRECCION>
     <CP>11690</CP>
     <LOCALIDAD>OLVERA</LOCALIDAD>
     <TLF_FIJO>95630316</TLF_FIJO>
     <TLF_MOVIL>69619915</TLF_MOVIL>
   </EMPLEADO>
   <EMPLEADO>
     <NOMBRE>MIGUEL</NOMBRE>
     <APELLIDOS>BERENGUEL MARQUINA</APELLIDOS>
     <NIF>6182669F</NIF>
     <EMPRESA>MAGARIIT SERVICES, S.A.</EMPRESA>
     <DIRECCION>ALCALA LA REAL , CALLE</DIRECCION>
     <CP>11640</CP>
     <LOCALIDAD>BORNOS</LOCALIDAD>
     <TLF_FIJO>96304400</TLF_FIJO>
     <TLF_MOVIL>62676864</TLF_MOVIL>
   </EMPLEADO>
</EMPLEADOS>
El código Java para recorrer y mostrar su contenido siguiendo el modelo DOM es el siguiente:
try {
    DocumentBuilderFactory fábricaCreadorDocumento = DocumentBuilderFactory.newInstance();
    DocumentBuilder creadorDocumento = fábricaCreadorDocumento.newDocumentBuilder();
    Document documento = creadorDocumento.parse("empleados.xml");
    //Obtener el elemento raíz del documento
    Element raiz = documento.getDocumentElement();
    //Obtener la lista de nodos que tienen etiqueta "EMPLEADO"
    NodeList listaEmpleados = raiz.getElementsByTagName("EMPLEADO");
    //Recorrer la lista de empleados
    for(int i=0; i&lt;listaEmpleados.getLength(); i++) {   
        //Obtener de la lista un empleado tras otro
        Node empleado = listaEmpleados.item(i);
        System.out.println("Empleado "+i);
        System.out.println("==========");    

        //Obtener la lista de los datos que contiene ese empleado
        NodeList datosEmpleado = empleado.getChildNodes();
        //Recorrer la lista de los datos que contiene el empleado
        for(int j=0; j&lt;datosEmpleado.getLength(); j++) {
            //Obtener de la lista de datos un dato tras otro
            Node dato = datosEmpleado.item(j);
            //Comprobar que el dato se trata de un nodo de tipo Element
            if(dato.getNodeType()==Node.ELEMENT_NODE) {
                //Mostrar el nombre del tipo de dato
                System.out.print(dato.getNodeName()+": ");
                //El valor está contenido en un hijo del nodo Element
                Node datoContenido = dato.getFirstChild();                        
                //Mostrar el valor contenido en el nodo que debe ser de tipo Text
                if(datoContenido!=null &amp;&amp; datoContenido.getNodeType()==Node.TEXT_NODE)
                    System.out.println(datoContenido.getNodeValue());
            }
        }
        //Se deja un salto de línea de separación entre cada empleado
        System.out.println();
    }
 
} catch (SAXException ex) {
    System.out.println("ERROR: El formato XML del fichero no es correcto\n"+ex.getMessage());
    ex.printStackTrace();
} catch (IOException ex) {
    System.out.println("ERROR: Se ha producido un error el leer el fichero\n"+ex.getMessage());
    ex.printStackTrace();
} catch (ParserConfigurationException ex) {
    System.out.println("ERROR: No se ha podido crear el generador de documentos XML\n"+ex.getMessage());
    ex.printStackTrace();
}
Se obtiene por la salida estándar algo similar a lo siguiente:
Empleado 0
==========
NOMBRE: LUIS MIGUEL
APELLIDOS: GALLARDO LEON
NIF: 5674179P
EMPRESA: DATATONIC, S.A.
DIRECCION: HERMANOS ARAGON , CALLE
CP: 11690
LOCALIDAD: OLVERA
TLF_FIJO: 95630316
TLF_MOVIL: 69619915

Empleado 1
==========
NOMBRE: MIGUEL
APELLIDOS: BERENGUEL MARQUINA
NIF: 61826629F
EMPRESA: MAGARIIT SERVICES, S.A.
DIRECCION: ALCALA LA REAL , CALLE
CP: 11640
LOCALIDAD: BORNOS
TLF_FIJO: 96304400
TLF_MOVIL: 62676864
Fuente:http://javiergarbedo.es/programacion-en-java/53-xml/247-ejemplo-de-lectura-de-fichero-xml-usando-dom
Tomar en cuenta al momento de importar las librerías necesarios tales como:
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

Comentarios

Entradas populares de este blog

JAVASCRIPT - DESHABILITAR RETROCESO, CONTROLAR REFRESH DE PÁGINA

TIPOS DE DATOS POSTGRES

PROBLEMA LICENCIAS TERMINAL SERVER Y WINDOWS SERVER 2012