Java JDOM Element detach() Method



The Java JDOM detach() method of Element class detaches the element from it's parent element and returns the detached element. When this method is used with the root element, the entire XML content gets removed as all elements should be contained inside a root element.

Syntax

Following is the syntax of the Java JDOM Element detach() method −

Element.detach();

Parameters

The Java detach() method doesn't accept any parameter.

Return Value

The Java detach() method returns the detached Element.

Example

Here is the sample.xml file we need to parse −

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <child>I'm the child</child>
</root>

The following basic example uses the Java JDOM Element detach() method to remove the child element.

import java.io.File;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

public class detachElement {
   public static void main(String args[]) {
      try {	
    	 //Reading the document
    	 SAXBuilder saxBuilder = new SAXBuilder();
    	 File inputFile = new File("sample.xml");
    	 Document doc = saxBuilder.build(inputFile);
    	 Element root = doc.getRootElement();
    	 Element child = root.getChild("child");
	     //detach child element
	     child.detach();
	     //Print the document
	     XMLOutputter xmlOutput = new XMLOutputter();
	     xmlOutput.setFormat(Format.getPrettyFormat());
	     xmlOutput.output(doc, System.out);       
      } catch (Exception e) {
    	 e.printStackTrace();
      }
   }
}

The document after removing the root gets displayed.

<?xml version="1.0" encoding="UTF-8"?>
<root />

Example 2

The detach() method when used with the root element removes the entire content inside it. Only the comments, DocType declaration and processing instruction which are outside the root element remains.

import java.io.File;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

public class detachRootElement {
   public static void main(String args[]) {
      try {	
    	 //Reading the document
    	 SAXBuilder saxBuilder = new SAXBuilder();
    	 File inputFile = new File("sample.xml");
    	 Document doc = saxBuilder.build(inputFile);
    	 Element root = doc.getRootElement();
	     //detach root
	     root.detach();
	     //Print the document
	     XMLOutputter xmlOutput = new XMLOutputter();
	     xmlOutput.setFormat(Format.getPrettyFormat());
	     xmlOutput.output(doc, System.out);       
      } catch (Exception e) {
    	 e.printStackTrace();
      }
   }
}

Only the processing instruction that remains inside the document is displayed.

<?xml version="1.0" encoding="UTF-8"?>
Advertisements