← Volver

XML en Java

Publicado el 14 de febrero de 2026

Primero creamos la ruta al fichero que vamos a leer/escribir.

String rutaRaiz = System.getProperty("user.dir");

String rutaArchivo = rutaRaiz + File.separator + "src" + File.separator + "archivos" + File.separator + "amistades.xml";

Creamos el grupo de personas.

Grupo amistades = new Grupo();

amistades.add(new Persona("Pepe", 25));
amistades.add(new Persona("Juan", 20));
amistades.add(new Persona("Maria", 45));
amistades.add(new Persona("Pedro", 33));

Creamos el documento, añadimos los elementos XML y grabamos.

 try {
            //ESCRIBIR DOCUMENTO XML
            //PASO 1: CREAR Y CONSTRUIR EL DOCUMENTO XML
            Document docAmistades = crearDocumentoXML("amistades");

            //PASO 2: CREAR ELEMENTOS PARA CADA AMISTAD
            addElementosXML(docAmistades, amistades);

            //PASO 3: GRABAR EL DOCUMENTO XML
            grabarDocXML(docAmistades, rutaArchivo);

        } catch (ParserConfigurationException |TransformerConfigurationException e) {
            System.out.println(e.getMessage());
        } catch (TransformerException e) {
            throw new RuntimeException(e);
        }

Crear el documento.

private static Document crearDocumentoXML(String nombreRoot) throws ParserConfigurationException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document docXML = builder.newDocument();
        Element root = docXML.createElement(nombreRoot);
        docXML.appendChild(root);

        return docXML;
    }

Añadir elementos.

 private static void addElementosXML(Document docAmistades, Grupo amistades) {
        Element rootElement = docAmistades.getDocumentElement();

        for (Persona p : amistades.getGrupo()){
            Element amistadElement = docAmistades.createElement(p.getClass().getSimpleName().toLowerCase());
            rootElement.appendChild(amistadElement);

            Element nombrePersona = docAmistades.createElement("nombre");
            amistadElement.appendChild(nombrePersona);

            nombrePersona.appendChild(docAmistades.createTextNode(p.getNombre()));

            Element edadPersona = docAmistades.createElement("edad");
            amistadElement.appendChild(edadPersona);

            edadPersona.appendChild(docAmistades.createTextNode(p.getEdad()+""));
        }


    }

Grabar documento XML.

 private static void grabarDocXML(Document docAmistades, String rutaArchivo) throws TransformerException {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer =  transformerFactory.newTransformer();

        DOMSource source = new DOMSource(docAmistades);

        StreamResult result = new StreamResult(new File(rutaArchivo));
        transformer.transform(source, result);

        System.out.println("Archivo grabado correctamente");

    }

Leer el archivo XML, cargarlo en el documento y obtener datos.

    try {
     //LEER DOCUMENTO XML AL DOM
        //PASO 1: LEER ARCHIVO XML Y CARGARLO EN UN DOCUMENT

            Document documentLeido = leerXML(rutaArchivo);
            //PASO 2: OBTENER AMISTADES
            Grupo amistades2 = obtenerAmistades(documentLeido);
            System.out.println(amistades2);

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

Leer el XML.

    private static Document leerXML(String rutaArchivo) throws ParserConfigurationException, IOException, SAXException {

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = dbFactory.newDocumentBuilder();

        Document document = documentBuilder.parse(new File(rutaArchivo));
        return document;

    }

Obtener datos.

private static Grupo obtenerAmistades(Document documentLeido) {
        Grupo amistades = new Grupo();
        Element raiz = documentLeido.getDocumentElement();
        NodeList listaPersona = raiz.getElementsByTagName("persona");
        String nombre = "";
        int edad = 0;

        for(int i=0; i < listaPersona.getLength(); i++){
           Node persona = listaPersona.item(i);
           NodeList datosPersona = persona.getChildNodes();
            for (int j = 0; j < datosPersona.getLength(); j++) {
                Node dato = datosPersona.item(j);
                if(dato.getNodeType() == Node.ELEMENT_NODE){
                    Node contenidoNodo = dato.getFirstChild();
                    String valorNodo = contenidoNodo.getNodeValue();
                    if(j == 0){
                        nombre = valorNodo;
                    }else{
                        edad = Integer.parseInt(valorNodo);
                    }
                }
            }

            amistades.add(new Persona(nombre, edad));

        }

        return amistades;


    }