Java JDOM Document hasRootElement() Method



The Java JDOM hasRootElement() method of Document class checks if the root element is present inside an XML document. It returns true if there is a root element and false if there is no root element.

Syntax

Following is the syntax of the Java JDOM Document hasRootElement() method −

Document.hasRootElement();

Parameters

The Java hasRootElement() method doesn't accept any parameters.

Return Value

The Java hasRootElement() method returns a Boolean value.

Example 1

Following is the basic example that illustrates the usage of the Java JDOM Document hasRootElement() method −

import org.jdom2.Document;

public class HasRootElement {
   public static void main(String args[]) {
      try {	
    	 //Creating a new Document
	     Document doc = new Document();
	     //checking the root
	     Boolean hasRoot = doc.hasRootElement();
	     System.out.println("Has Root? "+hasRoot);
      } catch (Exception e) {
    	 e.printStackTrace();
      }
   }
}

The output window displays false, since there is no root.

Has Root? false

Example 2

Now, let us add the root element to the document and use the hasRootElement() method to check if it displays true.

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

public class HasRootElement {
   public static void main(String args[]) {
      try {	
    	 //Creating a new Document and adding the root
	     Document doc = new Document();
	     Element element = new Element("root");
	     doc.addContent(element);
	     //checking the root
	     Boolean hasRoot = doc.hasRootElement();
	     System.out.println("Has Root? "+hasRoot);
      } catch (Exception e) {
    	 e.printStackTrace();
      }
   }
}

The output window displays true, since we have added the root.

Has Root? true
Advertisements