Delete A Node From XML File (DOM4J, JAVA)

Since all other questions related to this topic relate to a specific programming problem (for example, “I get a NullPointerException when trying this and that”), and the answers to them fix programming errors, here is a simple solution to the following question:

How to remove node from XML file using DOM4J?

+4
source share
2 answers

Assuming you already have the node you want to remove:

  Document document = node.getDocument();

  node.detach();

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

The try-catch statement is not specified.

Brief explanation:

  • Getting the document and saving it in a local variable is necessary because after disconnecting the node, you cannot receive the document by calling node.getDocument ()
  • detach() node node ( )
  • XMLWriter OutputFormat.createPrettyPrint() ,

, 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

+5

node 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");
    }
}
0

All Articles