【问题标题】:How to remove a XML node using JDOM?如何使用 JDOM 删除 XML 节点?
【发布时间】:2015-05-06 09:54:42
【问题描述】:

这是我的代码:

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

我需要在保存变量中的值后删除节点,我该怎么做?

【问题讨论】:

  • 在 StackOverflow 上发布代码时,请不要使用非英文标识符名称,因为这会使代码更难阅读。
  • 你想删除某个父节点的任何特定节点或子节点吗?提供更多信息。
  • 是的,每次我在厕所时的实际节点
  • 在 Element 上调用 removeChild() 应该很容易
  • removeChild 需要一个字符串,我该怎么办?

标签: java xml jdom


【解决方案1】:

“删除”节点有几个不同的含义。您可以从内存中的 JDOM 模型中删除节点,此外,您可以在没有节点的情况下覆盖磁盘上的文件,以保存修改后的文档。

要从 XML 文档中删除节点,您可以“分离”它:

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

分离 tabla 元素后,它将不再是内存文档的一部分,但您仍然可以将 tabla 引用为 XML 的“片段”。

如果要将修改后的文档保存回文件,则需要将 XML 写回文件:

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

此外,您确实应该使用 JDOM 2.x,其中泛型有助于使您的代码更整洁:

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

【讨论】:

  • 我按照你说的做了,但节点仍在文档中,我不知道为什么
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-05
  • 2021-05-31
  • 1970-01-01
相关资源
最近更新 更多