简体   繁体   中英

Remove A Node From XML File (DOM4J, JAVA)

Since all other questions related to this topic refer to a specific programming problem (eg '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:

  1. 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()
  2. calling detach() on the node will remove the node from the document object (not from the file)
  3. 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM