Java and J2EE Tutorials, Jsp and Servlet Tutorials, Spring MVC, Solr, XML, JSON Examples, Hibernate & Struts 2 Hello World projects



Thursday, 13 June 2013

Jdom 2 Xml Parser - Read xml and Create xml in Java

Jdom is the most developer friendly XML parser to read and create an xml file in Java. Jdom's programming friendly nature provides mechanism and implementation that makes it easy to xml parsing for java developers. JDOM uses one of the two mechanism, DOM or SAX to parse an xml but using JDOM we uses SAX and JDOM from its own and not the one provided by JDK itself.

JDOM is not available internally in JDK so we need to add an external jar to start with it, Jdom2 jar can be downloaded from HERE.

In today's discussion we will see step by step implementation of Jdom2 parser to make it possible, read xml and create xml in Java.


Jdom2 xml parser project structure

Here is the overall project structure for today's discussion, we have added an external jar file in 'lib' folder to take advantage of jdom2. Please make sure that the jar is included in classpath. 'xmlToParse' folder contains a sample xml file that we will read using jdom. 'generatedXmlFile' folder contains the created xml file from java code. 'CreateXml.java' file contains code for creating xml file and 'ReadXml.java' file contains code for parsing and reading xml in java.




How to Read xml in Java using Jdom2

Reading xml in java using jdom is a very simple process we just need to implement any of the two either DOM or SAX object, in our case we have used SAX.


Objective xml file to parse

Here is the sample xml document that we are going to parse and write the content on console.
<?xml version="1.0" encoding="UTF-8"?>
<school>
 <student id="1">
  <firstname>ankush</firstname>
  <lastname>thakur</lastname>
  <email>beingjavaguy.gmail.com</email>
  <phone>7678767656</phone>
 </student>
 <student id="2">
  <firstname>aarti</firstname>
  <lastname>gupta</lastname>
  <email>aartigupta.gmail.com</email>
  <phone>9876546545</phone>
 </student>
</school>



src\com\beingjavaguys\core\ReadXml.java

This class shows actual implementation of jdom2 parser in java, see the code below to understand how to use jsom2 in xml parser:
package com.beingjavaguys.core;

import java.io.File;
import java.io.IOException;
import java.util.List;

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


public class ReadXml {
 public void getXml(){
  
  // reading can be done using any of the two 'DOM' or 'SAX' parser
  // we have used saxBuilder object here
  // please note that this saxBuilder is not internal sax from jdk
     SAXBuilder saxBuilder = new SAXBuilder();
     
     // obtain file object 
     File file = new File("xmlToParse/student.xml");

  try {
   // converted file to document object
   Document document = saxBuilder.build(file);
   
   // get root node from xml
   Element rootNode = document.getRootElement();
   
   // got all xml elements into a list
      List<Student> studentList = rootNode.getChildren("student");
      
      // simple iteration to see the result on console
      for(int i=0;i<=studentList.size()-1;i++){
       Element element = studentList.get(i);
       System.out.println("First Name : "+element.getChildText("firstname"));
       System.out.println("Last Name : "+element.getChildText("lastname"));
       System.out.println("Email : "+element.getChildText("email"));
       System.out.println("Phone : "+element.getChildText("phone"));
      }
     
  } catch (JDOMException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }  
 }
}




Output

This is the output printed on console, all data that is being read from example xml is shown here :




How to Create xml file in Java using Jdom2

Create xml file in java using jdom2 is a very simple process, see the example below most of the code is explained through comments :

Objective xml file to create

This is the objective xml file that we will create using jdom2 capabilities:
<?xml version="1.0" encoding="UTF-8"?>
<school>
 <student id="1">
  <firstname>ankush</firstname>
  <lastname>thakur</lastname>
  <email>beingjavaguy@gmail.com</email>
  <phone>8788987656</phone>
 </student>
</school>




src\com\beingjavaguys\core\CreateXml.java

This class shows actual implementation of jdom2 parser in java to implement how to create xml file in java, see the code below to understand jdom parser:
package com.beingjavaguys.core;

import java.io.FileWriter;
import java.io.IOException;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

public class CreateXml {

 public void createXml() {

  try {
   // returns an xml element object
   // school is passed to make it root element in document
   Element school = new Element("school");

   // created an document object, all elements will be added to it
   // passes school as parameter to make it root element of document
   Document document = new Document(school);

   // created other element to add to document
   Element student = new Element("student");

   // adding child attribute to student element
   student.setAttribute(new Attribute("id", "1"));
   student.addContent(new Element("firstname").setText("ankush"));
   student.addContent(new Element("lastname").setText("thakur"));
   student.addContent(new Element("email")
     .setText("beingjavaguy@gmail.com"));
   student.addContent(new Element("phone").setText("8788987656"));

   // get root element and added student element as a child of it
   document.getRootElement().addContent(student);

   // get object to see output of prepared document
   XMLOutputter xmlOutput = new XMLOutputter();

   // passsed System.out to see document content on console
   xmlOutput.output(document, System.out);

   // passed fileWriter to write content in specified file
   xmlOutput.setFormat(Format.getPrettyFormat());
   xmlOutput.output(document, new FileWriter(
     "generatedXmlFiles/generatedXml.xml"));

  } catch (IOException io) {
   System.out.println(io.getMessage());
  }
 }
}




Implementation class code

This is a simple implementation class to see the things working.

src\com\beingjavaguys\core\JdomImplementation.java

We have called two classes here, please make sure to commented out one by one to see exact implementation.
package com.beingjavaguys.core;

public class JdomImplementation {

 public static void main(String[] args) {
  
  // read xml from a file
  ReadXml readXml = new ReadXml();
  readXml.getXml();
  
  // write xml to a file
  CreateXml createXml = new CreateXml();
  createXml.createXml();
 }
}



In this particular blog we cam across 'How to read xml in java using jdom2 parser' & 'how to create an xml file in java' and 'how to use jdom2 for xml parsing'. In upcoming blogs we will come across more about more Xml parser in Java and their implementation. To know about DOM and SAX implementation in Java click Here. Read more about XML & JSON under SAX & DOM & XML parser in Java JSON, and JAXB - Marshalling & Unmarshalling in Java categories.








Thanks for reading !
Being Java Guys Team

Download "JDOM2 parser in Java Example Project" from "SkyDrive"





5 comments:

  1. very useful content explained in a good manner. keep it up

    ReplyDelete
  2. Very useful and relevant. Thank you!!
    Gio

    ReplyDelete
  3. Where does the Student type come from? Or is that a typo?

    ReplyDelete

Like Us on Facebook


Like Us On Google+



Contact

Email: neel4soft@gmail.com
Skype: neel4soft