Home Tutorial Xml Jdom JDOM Element Example, How to get text of element of xml file.

 
 

Share on Google+Share on Google+
JDOM Element Example, How to get text of element of xml file.
Posted on: August 26, 2010 at 12:00 AM
Advertisement
In this tutorial, you will see how to get text of element of xml file.

JDOM Element Example, How to get text of element of xml file.

In this tutorial, we will see how to get text value of an element from xml file by using JDOM toolkit. JDOM is a library used for manipulating xml file.

In this example we are create xml document with the help of SAXBuilder class. The SAXbuilder class builds the Document tree with the help of xml string. Example then reads the value of an element. The class SAXBulider is used for creating JDOM tree with the help of build() method. The getChild() method of Element class is used to get the child of given element. The getText() method returns text value of the element.

Code:

GetElementText.java

package roseindia;
import org.jdom.input.SAXBuilder;
import org.jdom.Document;
import org.jdom.Element;
import java.io.StringReader;

public class GetElementText {
  public static void main(String[] args) {
    String xml = "<BookCatalog>" "<book name=\"java\">"
    "This is programming language book." "</book>"    
    "</BookCatalog>";
    SAXBuilder builder = new SAXBuilder();
    try {
      Document document = builder.build(new StringReader(xml));
      Element root = document.getRootElement();
      Element childBook = root.getChild("book");
      String text = childBook.getText();
      System.out.println("Text : " + text);
      String textTrim = childBook.getTextTrim();
      System.out.println("After trim Text : " + textTrim);
      String textNormalize = childBook.getTextNormalize();
      System.out.println("After normalization Text :" 
     
+ textNormalize);
    catch (Exception e) {
      System.out.println(e);
    }
  }
}

Output:

Text : This is programming language book.
After trim Text : This is programming language book.
After normalization Text :This is programming language book.

Download this code

Advertisement

Related Tags for JDOM Element Example, How to get text of element of xml file.:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: August 26, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com