Java JDOM Parser - Parse XML Document


Steps to Using JDOM

Following are the steps used while parsing a document using JDOM Parser.

  • Import XML-related packages.

  • Create a SAXBuilder

  • Create a Document from a file or stream

  • Extract the root element

  • Examine attributes

  • Examine sub-elements

Import XML-related packages

import java.util.*;
import org.jdom2.*;

Create a DocumentBuilder

SAXBuilder saxBuilder = new SAXBuilder();

Create a Document from a file or stream

File inputFile = new File("input.txt");
SAXBuilder saxBuilder = new SAXBuilder();
Document document =;

Extract the root element

Element classElement = document.getRootElement();

Examine attributes

//returns specific attribute

Examine sub-elements

//returns a list of subelements of specified name
//returns a list of all child nodes
//returns first child node

Demo Example

Here is the input xml file we need to parse:

<?xml version="1.0"?>
   <student rollno="393">
   <student rollno="493">
   <student rollno="593">

Demo Example:

import java.util.List;

import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

public class JDomParserDemo {
   public static void main(String[] args) {
      try {
         File inputFile = new File("input.txt");

         SAXBuilder saxBuilder = new SAXBuilder();

         Document document =;

         System.out.println("Root element :" 
            + document.getRootElement().getName());

         Element classElement = document.getRootElement();

         List<Element> studentList = classElement.getChildren();

         for (int temp = 0; temp < studentList.size(); temp++) {    
            Element student = studentList.get(temp);
            System.out.println("\nCurrent Element :" 
               + student.getName());
            Attribute attribute =  student.getAttribute("rollno");
            System.out.println("Student roll no : " 
               + attribute.getValue() );
            System.out.println("First Name : " + student.getChild("firstname").getText());
            System.out.println("Last Name : "+ student.getChild("lastname").getText());
            System.out.println("Nick Name : "+ student.getChild("nickname").getText());
            System.out.println("Marks : "+ student.getChild("marks").getText());	            		
      }catch(JDOMException e){
      }catch(IOException ioe){

This would produce the following result:

Root element :class

Current Element :student
Student roll no : 393
First Name : dinkar
Last Name : kad
Nick Name : dinkar
Marks : 85

Current Element :student
Student roll no : 493
First Name : Vaneet
Last Name : Gupta
Nick Name : vinni
Marks : 95

Current Element :student
Student roll no : 593
First Name : jasvir
Last Name : singn
Nick Name : jazz
Marks : 90