Since all other questions related to this topic refer to a specific programming problem (e.g. 'I get a NullPointerException when I try this and that') and the answers are fixing the programming errors, here is a simple solution to the following question:
How can I delete a node from an XML file using DOM4J?
Assuming you already have the node you want to delete:
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 omitted.
Short explanation:
For a more complete example, here is a JUnit test:
@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();
}
For more information regarding DOM4J refer to: http://dom4j.sourceforge.net/dom4j-1.6.1/guide.html
And more information for XPath syntax: http://www.w3schools.com/xsl/xpath_syntax.asp