0

这是我的代码:

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

我有一些问题,我认为如果我从实际节点分离我无法进入下一个节点,那么我正在尝试找到删除前一个节点并删除和循环的乞求的方法,如何我可以做吗?

4

1 回答 1

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.
....
于 2015-05-07T10:51:52.187 回答