marcss
marcss

Reputation: 253

How to remove a XML node using JDOM?

Here is my code:

try
{
    Document fichero = (Document) builder.build( xmlFile );
    Element rootNode = fichero.getRootElement();
    List list = rootNode.getChildren( "fichada" );
    for ( int i = 0; i < list.size(); i++ )
    {
        Element tabla = (Element) list.get(i);
        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 NODE 
    }
} catch ( IOException io ) {
    System.out.println( io.getMessage() );
} catch ( JDOMException jdomex ) {
    System.out.println( jdomex.getMessage() ); 
}

I need to delete the node just after saving the values in the variables, how can I do it?

Upvotes: 0

Views: 1140

Answers (1)

rolfl
rolfl

Reputation: 17707

"Deleting" the node has a couple of different meanings. You can remove the node from the in-memory JDOM model, and additionally, you can then overwrite the file on disk without the node, to save the modified document.

To remove the node from the XML document, you 'detach' it:

.....
String caus = tabla.getChildTextTrim("Causa");
tabla.detach();

After you detach the tabla element it will no longer be part of the in-memory document, but you can still reference tabla as a 'fragment' of XML.

If you want to save the modified document back to the file, you will need to write the XML back to the file:

try (FileOutputStream fos = new FileOutputStream(xmlfile)) {
    XMLOutputter xmlout = new XMLOutputter();
    xmlout.output(fichero, fos);
}

Additionally, you really should be using JDOM 2.x where generics will help make your code neater:

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 NODE 
        tabla.detach();
    }
} catch ( IOException io ) {
    System.out.println( io.getMessage() );
} catch ( JDOMException jdomex ) {
    System.out.println( jdomex.getMessage() ); 
}

Upvotes: 1

Related Questions