Cómo Recorrer Archivo XML en Java

Por aquí dejo algunos apuntes XML, para recorrer nuestro archivo XML. Para ello debemos tener nuestro archivo XML. Para ello voy a usar el siguiente XML de ejemplo:

Aquí dejo el código que he usado en Java:

try {
             DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
 // Creo un documentBuilder
             DocumentBuilder builder = factory.newDocumentBuilder();
             Document documento = builder.parse(new File("archivoxml.xml"));
             NodeList nList = documento.getElementsByTagName("libro");
         for (int temp = 0; temp < nList.getLength(); temp++) {             Node nNode = nList.item(temp);             if (nNode.getNodeType() == Node.ELEMENT_NODE) {                 Element eElement = (Element) nNode;                 System.out.println("\nID: " + eElement.getAttribute("id"));                 System.out.println("\nTitulo: "                         + eElement.getElementsByTagName("titulo").item(0).getTextContent());                 System.out.println("\nAutor: "                         + eElement.getElementsByTagName("autor").item(0).getAttributes().getNamedItem("nombre").getTextContent());                 System.out.println("\nDescripcion: "                         + eElement.getElementsByTagName("descripcion").item(0).getTextContent());             }         }     } catch (Exception ex) {         System.out.println("Error " + ex.getMessage());     }

Por aquí dejo mis mini-apuntes de programación.

Deja un comentario

Información básica sobre protección de datos Ver más

  • Responsable: Tomas Gonzalez.
  • Finalidad:  Moderar los comentarios.
  • Legitimación:  Por consentimiento del interesado.
  • Destinatarios y encargados de tratamiento:  No se ceden o comunican datos a terceros para prestar este servicio.
  • Derechos: Acceder, rectificar y suprimir los datos.
  • Información Adicional: Puede consultar la información detallada en la Política de Privacidad.

error: Content is protected !!

Descubre más desde InfoGonzalez - Blog de formador e informático

Suscríbete ahora para seguir leyendo y obtener acceso al archivo completo.

Seguir leyendo

Este sitio web utiliza cookies, si necesitas más información puedes visitar nuestra política de privacidad    Ver
Privacidad
Creative Commons License
Except where otherwise noted, the content on this site is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.