Reputation: 1490
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?
Upvotes: 4
Views: 2637
Reputation: 3377
To remove a node with XPath, this is how you can do in 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");
}
}
Upvotes: 0
Reputation: 1490
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
Upvotes: 6