Search code examples
javaxmljdomjdom-2

delete the previous node in java using jdom


Here is my code:

SAXBuilder builder = new SAXBuilder();
File xmlFile = new File( "fichadas.xml" );
try
{
    Document fichero = (Document) builder.build( xmlFile );
    Element rootNode = fichero.getRootElement();
    for (Element tabla : rootNode.getChildren( "fichada" )) {
        String term = tabla.getChildTextTrim("N_Terminal");
        String tarj = tabla.getChildTextTrim("Tarjeta");
        String fech = tabla.getChildTextTrim("Fecha");
        String horaEnXML = tabla.getChildTextTrim("Hora");
        String caus = tabla.getChildTextTrim("Causa");    

        //HERE I WANT TO DELETE THE PREVIOUS NODE NOT THE ACTUAL
        tabla.detach();

    }
    //OVERWRITING THE DOCUMENT
    try (FileOutputStream fos = new FileOutputStream("fichadas.xml")) {
        XMLOutputter xmlout = new XMLOutputter();
        xmlout.output(fichero, fos);
    }
} catch ( IOException io ) {
    System.out.println( io.getMessage() );
} catch ( JDOMException jdomex ) {
    System.out.println( jdomex.getMessage() ); 
}

I have some problems, i think that if i made the detach from the actual node i can't go to the next, then i'm trying to find the way to delete the previous node and delete and the begging of the loop, how can i do it?


Solution

  • JDOM 2.x is fully compatible with the Collections API and if you want to remove elements while, or after you loop through them all, then you have a few options.

    First up is an Iterator, calling the remove() method during iteration....

    for (Iterator<Element> tabit = rootNode.getChildren( "fichada" ).iterator();
            tabit.hasNext(); ) {
    
        Element tabla = tabit.next();
        // safely remove one-at-a-time from the document.
        tabit.remove();
        ......
    
    }
    
    // write the modified document back to disk.
    ....
    

    Alternatively, you can clear the list of nodes to delete:

    Document fichero = (Document) builder.build( xmlFile );
    Element rootNode = fichero.getRootElement();
    List<Element> toProcess = rootNode.getChildren( "fichada" );
    
    for (Element tabla : toProcess) {
        .....
    }
    // remove all processed nodes from the in-memory document.
    toProcess.clear();
    
    // write the modified document back to disk.
    ....