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

delete the previous node in java using jdom

这是我的代码:

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

我有一些问题,我想如果我从实际节点分离我不能去下一个,然后我试图找到删除前一个节点并删除和请求的方法循环,我该怎么做?

JDOM 2.x 与集合完全兼容 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.
....