Java JDOM Element getContentSize() Method



The Java JDOM getContentSize() method of Element class is used to get the number of content objects inside an XML Element. These content objects include child elements, comments, text etc. This method also counts the whitespaces as an empty text.

Syntax

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

Element.getContentSize();

Parameters

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

Return Value

The Java getContentSize() method returns the number of content objects in the form of an integer.

Example 1

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

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

public class GetContentSize {
   public static void main(String args[]) {
      try {	
    	 //Create Document and add root
	     Document doc = new Document();
	     Element root = new Element("root").setText("I'm the root");
	     doc.setRootElement(root);
	     //Get content size of root
	     int contentSize = root.getContentSize();
    	 System.out.println("No.of content objects : "+contentSize);	     
      } catch (Exception e) {
    	 e.printStackTrace();
      }
   }
}

The number of content objects inside the root is displayed.

No.of content objects : 1

Example 2

We need to parse the following library.xml file −

<library>
	Readers choice 
	<!--Book information is available here -->
   <book>War and peace</book>
</library>

The getContentSize() method counts the whitespace as an empty text and returns the result.

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

public class GetContentSize {
   public static void main(String args[]) {
      try {
         //Reading the document and get the root
    	 SAXBuilder saxBuilder = new SAXBuilder();
    	 File inputFile = new File("library.xml");
    	 Document doc = saxBuilder.build(inputFile);
    	 Element root = doc.getRootElement();
    	 //Get content size
    	 int contentSize = root.getContentSize();
    	 System.out.println("No.of content objects : "+contentSize);	  
      } catch(Exception e) {
    	 e.printStackTrace();
      }
   }
}

The output window displays the number of content objects.

No.of content objects : 5
Advertisements