Java JDOM Element getText() Method



The Java JDOM getText() method of Element class is used to get the text content of an XML Element. This method retrieves the exact text content including white spaces between the opening and closing tags of the element along with the CDATA section if exists.

Syntax

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

Element.getText();

Parameters

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

Return Value

The Java getText() method returns the text content of an Element in the form of a string.

Example 1

The following basic example explains the usage of Java JDOM Element getText() method −

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

public class GetTextContent {
   public static void main(String args[]) {
      try {	
    	 //Create a new Document
	     Document doc = new Document();
	     //Create and add root
	     Element root = new Element("book").setText("War and Peace");
	     doc.setRootElement(root);
	     //Get text content
	     String textContent = root.getText();
	     System.out.println("Text Content: "+textContent);       
      } catch (Exception e) {
    	 e.printStackTrace();
      }
   }
}

Text content of the root element is displayed.

Text Content: War and Peace

Example 2

The getText() method returns an empty string if there is no text content for the XML element.

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

public class GetTextContent {
   public static void main(String args[]) {
      try {	
    	 //Create a new Document
	     Document doc = new Document();
	     //Create and add root
	     Element root = new Element("book");
	     doc.setRootElement(root);
	     //Get text content
	     String textContent = root.getText();
	     System.out.println("Text Content: "+textContent);       
      } catch (Exception e) {
    	 e.printStackTrace();
      }
   }
}

An empty string is displayed as text content.

Text Content:

Example 3

The following htmlTable.xml file has CDATA section. We need to parse this XML file.

<htmlTable>
   <![CDATA[<table>]]> - HTML table tag.
</htmlTable>

The getText() method returns the text, whitespaces and the CDATA section if available for the XML Element.

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

public class GetTextContent {
   public static void main(String args[]) {
      try {	
    	 //Reading the document
    	 SAXBuilder saxBuilder = new SAXBuilder();
    	 File inputFile = new File("htmlTable.xml");
    	 Document doc = saxBuilder.build(inputFile);
	     //Get the root
	     Element root = doc.getRootElement();
	     //Get text content
	     String textContent = root.getText();
	     System.out.println("Text Content: "+textContent);       
      } catch (Exception e) {
    	 e.printStackTrace();
      }
   }
}

The CDATA section along with the text get displayed.

Text Content: 
<table> - HTML table tag.
Advertisements