2

I 'm trying to delete an element from an xml file, using removeChild(). Even though it says that operation is successful, it still exists and it can be printed.

DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();

        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(new File("/home/sr-user1/Téléchargements/Test/intense172E.xml"));

        Element output = (Element) doc.getElementsByTagName("output").item(0);

         output.getParentNode().removeChild(output);
         System.out.println(output.getTextContent());
sirine.ch
  • 29
  • 1
  • 7

2 Answers2

1

Node.removeChild(Node) does not invalidate the child node, it simply detaches it from the parent. The child can be used again and for instance added to another node.

wero
  • 32,544
  • 3
  • 59
  • 84
1

The method

 output.getParentNode().removeChild(output);     

will remove the node from the parent node (in your case, doc), but you will still have the information about the node. Since you are printing

 output.getTextContent()     

you are still receiving the text that was present in the node. You need to print the contents of doc to check that it was removed successfully from the original xml.

Edit: If you then want to modify the original xml file, you need to write it again by doing this:

 XMLOutputter xmlOutput = new XMLOutputter();
 xmlOutput.setFormat(Format.getPrettyFormat());
 xmlOutput.output(doc, new FileWriter("c:\\your_path\\file.xml"));
randombee
  • 699
  • 1
  • 5
  • 26
  • So how do I delete the node completely? – sirine.ch Feb 23 '16 at 09:51
  • Why do you want to do that? "output" is just a variable, it will get deleted by the java garbage collector at some point as long as you're not using it. As long as you don't have it in the original doc, why is that a problem? – randombee Feb 23 '16 at 09:54
  • That's the thing, I still have it in the original doc. – sirine.ch Feb 23 '16 at 09:57
  • Have you tried printing it? Because in this line System.out.println(output.getTextContent()); you're not testing that. – randombee Feb 23 '16 at 10:02
  • I can't find the XMLOutputter class there's only an XMLOutPutSource class and it doesn't have the setFormat() method. – sirine.ch Feb 23 '16 at 10:31
  • You can download jdom-2.0.6.jar from here http://www.jdom.org/downloads/, then import the jar as external library to your project and you will be able to use it. – randombee Feb 23 '16 at 10:41
  • If you don't want to use jdom, check the accepted answer in here http://stackoverflow.com/questions/4561734/how-to-save-parsed-and-changed-dom-document-in-xml-file – randombee Feb 23 '16 at 10:43