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:
- Getting the document and storing it in a local variable is needed,
because after detaching the node, you cannot get the document by
calling node.getDocument()
- calling detach() on the node will remove the node from the document object (not from the file)
- creating an XMLWriter with OutputFormat.createPrettyPrint() is needed, if you don't want any blank lines in your document afterwards
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