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