这是我的代码:
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 与 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.
....
关于java - java中使用jdom删除前一个节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30097827/