从 XML 文件中删除一个节点(DOM4J,JAVA)

Remove A Node From XML File (DOM4J, JAVA)

由于与此主题相关的所有其他问题都涉及特定的编程问题(例如 'I get a NullPointerException when I try this and that')并且答案是修复编程错误,这里是一个简单的以下问题的解决方案:

如何使用 DOM4J 从 XML 文件中删除节点?

假设您已经有要删除的节点:

  Document document = node.getDocument();

  node.detach();

  XMLWriter writer = new XMLWriter(new FileWriter(document.getPath() + document.getName()), OutputFormat.createPrettyPrint());
  writer.write(document);
  writer.close();

省略try-catch语句

简短说明:

  1. 需要获取文档并将其存储在局部变量中, 因为在分离节点后,您无法通过 调用 node.getDocument()
  2. 在节点上调用 detach() 将从文档对象(而不是文件)中删除该节点
  3. 如果您不想在您的文件中有任何空行,则需要使用 OutputFormat.createPrettyPrint() 创建一个 XMLWriter事后文件

有关更完整的示例,这是一个 JUnit 测试:

@Test
public void dom4j() throws DocumentException, IOException {
  String absolutePath = Paths.get(PATH_TO_XML).toAbsolutePath().toString();

  SAXReader reader = new SAXReader();
  Document document = reader.read(absolutePath);
  Node node = document.selectSingleNode(XPATH_TO_NODE);

  node.detach();

  XMLWriter writer = new XMLWriter(new FileWriter(absolutePath), OutputFormat.createPrettyPrint());
  writer.write(document);
  writer.close();
}

有关 DOM4J 的更多信息,请参阅: http://dom4j.sourceforge.net/dom4j-1.6.1/guide.html

以及有关 XPath 语法的更多信息:http://www.w3schools.com/xsl/xpath_syntax.asp

要使用 XPath 删除节点,您可以在 vtd-xml

中执行此操作
import com.ximpleware.*;
import java.io.*;

public class removeElement {
    public static void main(String s[]) throws VTDException,IOException{
        VTDGen vg = new VTDGen();
        if (!vg.parseFile("input.xml", false))
            return;
        VTDNav vn = vg.getNav();
        XMLModifier xm = new XMLModifier(vn);
        AutoPilot ap = new AutoPilot(vn);
        ap.selectXPath("/ClOrdIDS/ClOrdID[@id='3']");
        int i=0;
        while((i=ap.evalXPath())!=-1){
            xm.remove();
        }
        xm.output("output.xml");
    }
}