Java JDOM Element isRootElement() Method



The Java JDOM isRootElement() method of Element class is used to check whether an XML element is a root element. The root element has its parent set to the document. Hence, this method returns true when used with root elements. If this method is used after detaching the root element from the document, it returns false.

Syntax

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

Element.isRootElement();

Parameters

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

Return Value

The Java isRootElement() method returns a boolean value; true if it is root, false otherwise.

Example 1

Here is the basic example of using the Java JDOM Element isRootElement() method −

import org.jdom2.Document;
import org.jdom2.Element;

public class isRootElement {
   public static void main(String args[]) {
      try {	
    	 //Create Document and add root
    	 Document doc = new Document();
	     Element root = new Element("book");	     
	     doc.setRootElement(root);
	     //check if element is set as root
	     Boolean isRoot = root.isRootElement();
	     System.out.println("Is root element? "+isRoot);
      } catch (Exception e) {
    	 e.printStackTrace();
      }
   }
}

The boolean value returned by isRootElement() method is displayed.

Is root element? true

Example 2

In the following example, a child element is created and added to the root. Then the isRootElement() method is used with child element to observe the result.

import org.jdom2.Document;
import org.jdom2.Element;

public class isRootElement {
   public static void main(String args[]) {
      try {	
    	 //Create Document and add root
    	 Document doc = new Document();
	     Element root = new Element("book");
	     Element child = new Element("bookName");
	     root.setContent(child);
	     doc.setRootElement(root);
	     //check if child is root
	     Boolean isRoot = child.isRootElement();
	     System.out.println("Is root element? "+isRoot);
      } catch (Exception e) {
    	 e.printStackTrace();
      }
   }
}

The boolean value returned by isRootElement() method is displayed on the output screen.

Is root element? false
Advertisements