使用jdom删除java中的上一个节点

时间:2015-05-07 10:04:01

标签: java xml jdom jdom-2

这是我的代码:

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() ); 
}

我有一些问题,我认为如果我从实际节点分离我不能去下一个,那么我正试图找到删除前一个节点的方法并删除和乞讨的循环,我该怎么办?

1 个答案:

答案 0 :(得分:1)

JDOM 2.x与Collections API完全兼容,如果你想在删除元素时,或者在遍历它们之后删除元素,那么你有几个选项。

首先是迭代器,在迭代期间调用remove()方法....

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.
....

或者,您可以清除要删除的节点列表:

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.
....