【问题标题】:Remove A Node From XML File (DOM4J, JAVA)从 XML 文件中删除节点 (DOM4J, JAVA)
【发布时间】:2023-03-24 14:30:01
【问题描述】:

由于与该主题相关的所有其他问题都涉及特定的编程问题(例如,'我在尝试这个和那个时得到一个 NullPointerException')并且答案是修复编程错误,这里是以下问题的简单解决方案:

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

【问题讨论】:

    标签: java dom4j


    【解决方案1】:

    要使用 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");
        }
    }
    

    【讨论】:

    • 尽管我很欣赏新的解决方案:这不是问题的答案。这是对 How can I delete a node from an XML file using XPath and vtd-xml? 或标题 Remove A Node From XML File (XPATH, VTD-XML, JAVA)
    【解决方案2】:

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

      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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-19
      • 2018-03-17
      • 1970-01-01
      • 2016-11-05
      • 2020-01-15
      • 1970-01-01
      • 2012-11-30
      • 1970-01-01
      相关资源
      最近更新 更多