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.

Gracias por visitar mi blog de informática, mi nombre es Tomás y soy formador y desarrollador web. Si quiere usted dejarme alguna sugerencia, ayuda o quiere un servicio de formación estoy escuchando ofertas en tomas.gonzalez@infogonzalez.com, en Facebook a https://www.facebook.com/Infogonzalez estoy deseando escucharle. Su duda o sugerencia NO molesta.

Tomas Gonzalez
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.
A %d blogueros les gusta esto: