JAXB Tutorial

This article is an introductory tutorial for JAXB. Some time back I wrote a tutorial introducing Java StAX and after reading that lot of friends asked to write on JAXB and so this article.

JAXB is an acronym of Java Architecture for XML Binding. JAXB provides API to access and process a XML document. We can read or write XML files using JAXB. Unlike SAX, DOM parsers to use JAXB the developer need not be aware of XML parsing techniques.

XML Schema

Schema is a definition file for a XML document. It maintains the rule/syntax for a XML document. An XML document need not always have a schema. But if it has one it should adhere to its specifications.  While using JAXB XML schema is not a mandatory requirement. Process can start with java pojo classes. But it is convenient to have associated XML schema so that we can use a binding compiler and generate the java classes. That schema should be written using W3C XML Schema Language.

JAXB Implementation

JAXB API is a set of interfaces for which we have various implementations. As part of Metro there is a project for JAXB providing reference implementation. JSR 222 is developed by JCP for JAXB. Latest version of JAXB as of now is JAXB 2.2. As part of this artice I am using Metro’s JAXB reference implementation. To run the sample code associated, you should download jaxb implementation and the jar files to the classpath.

JAXB Binding

JAXB is middle man between XML document and java instances. Important step in using JAXB is creating java POJO classes. XML schema can be used by a JAXB binding compiler to generate java classes. Those generated java classes match the XML schema and they will be loaded at runtime in the application. If we don’t have the XML schema, then we can manually code the POJO classes and annotate with JAXB annotations. We can instantiate those classes then read or write to XML. XJC – com.sun.tools.xjc.XJCTask is the binding compiler provided by metro. The JAXB classes generated from an XML Schema are POJOs with the standard JAXB annotations. They are intended to be compatible with other JAXB implementations.

Ads by Google

Unmarshal and Marshal in JAXB

Unmarshal is the process of binding the XML document using JAXB compiler and generating mapping java classes then constructing the instances with values available in XML document.

Marshal is the reverse process of it. First we construct the instances and then write a XML document using the constructed instances.

In both the cases, we need create POJO classes first. If we have the XML schema that can be used to generate those classes using a JAXB binding compiler. If the XML schema is not available, then we should manually code those POJOs. Only then we can do unmarshal or marshal in an application.

Marshaling and unmarshaling can be done with other sources. That means, the XML need not be in file form. It can be a InputStream object, a URL, a DOM node, SAXSource.

To Unmarshal

  1. Create POJOs or bind the schema and generate the classes.
  2. Create a JAXBContext object. (javax.xml.bind.JAXBContext)
  3. Create an Unmarshaller object. (javax.xml.bind.Unmarshaller)
  4. Call the unmarshal method.
  5. Use the get methods available in schema-genearated classes to access the values.

To Marshal

  1. Create POJOs or bind the schema and generate the classes.
  2. Create the content tree by using set methods.
  3. Create a JAXBContext object. (javax.xml.bind.JAXBContext)
  4. Create a Marshaller object. (javax.xml.bind.Marshaller)
  5. Call the marshal method to persist the created content tree as XML document.

JAXB Unmarshal Sample

Download JAXBSample and Run

You need to download JAXB reference implementation from metro and add jar files inside the lib folder to run this sample.

Following is build.xml for the sample code. You can see that XJC is used to compile XSD and generate java classes.

<?xml version="1.0" standalone="yes"?>

<project basedir="." default="run">
  <property name="jaxb.home" value="." />
  <path id="classpath">
    <pathelement path="src" />
    <pathelement path="classes" />
    <pathelement path="schemas" />
    <fileset dir="${jaxb.home}" includes="lib/*.jar" />
  </path>
  <taskdef name="xjc" classname="com.sun.tools.xjc.XJCTask">
    <classpath refid="classpath" />
  </taskdef>

  <!--compile Java source files-->
  <target name="compile" description="Compile all Java source files">
    <echo message="Compiling the schema..." />
    <mkdir dir="gen-src" />
    <xjc schema="zoo.xsd" package="com.javapapers.xml.jaxb" destdir="gen-src">
      <produces dir="gen-src/com.javapapers.xml.jaxb" includes="**/*.java" />
    </xjc>
    <echo message="Compiling the java source files..." />
    <mkdir dir="classes" />
    <javac destdir="classes" debug="on">
      <src path="src" />
      <src path="gen-src" />
      <classpath refid="classpath" />
    </javac>
  </target>

  <target name="run" depends="compile" description="Run the sample app">
    <echo message="Running the sample application..." />
    <java classname="com.javapapers.xml.jaxb.JAXBUnmarshalSample" fork="true">
      <classpath refid="classpath" />
    </java>
  </target>

  <target name="javadoc" description="Generates javadoc" depends="compile">
    <echo message="Generating javadoc..." />
    <mkdir dir="docs/api" />
    <javadoc sourcepath="gen-src" destdir="docs/api" windowtitle="Using unmarshaller (formerly SampleApp1)" useexternalfile="yes">
      <fileset dir="." includes="gen-src/**/*.java" excludes="**/impl/**/*.java" />
    </javadoc>
  </target>

  <target name="clean" description="Deletes all the generated artifacts.">
    <delete dir="docs/api" />
    <delete dir="gen-src" />
    <delete dir="schemas" />
    <delete dir="classes" />
  </target>
</project>

Following the XSD

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <xsd:element name="zoo" type="zooInfo"/>
  <xsd:element name="comment" type="xsd:string"/>
  <xsd:complexType name="zooInfo">
    <xsd:sequence>
      <xsd:element name="zooName" type="xsd:string"/>
      <xsd:element name="zooId" type="xsd:int"/>
      <xsd:element name="animals" type="Animals"/>
    </xsd:sequence>
  </xsd:complexType>

  <xsd:complexType name="Animals">
    <xsd:sequence>
      <xsd:element name="animal" minOccurs="1" maxOccurs="unbounded">
        <xsd:complexType>
          <xsd:sequence>
            <xsd:element name="animalName" type="xsd:string"/>
            <xsd:element name="animalType" type="xsd:string"/>
          </xsd:sequence>
        </xsd:complexType>
      </xsd:element>
    </xsd:sequence>
  </xsd:complexType>
</xsd:schema>

The XML document which we are going to read and print in console:

<?xml version="1.0"?>
<zoo>
  <zooName>Vandalur Zoo</zooName>
  <zooId>12321</zooId>
  <animals>
    <animal>
      <animalName>Lion</animalName>
      <animalType>Wild</animalType>
    </animal>
    <animal>
      <animalName>Dog</animalName>
      <animalType>Domestic</animalType>
    </animal>
    <animal>
      <animalName>White Tiger</animalName>
      <animalType>Wild</animalType>
    </animal>
  </animals>
</zoo>

Following is the java code to read the XML file

package com.javapapers.xml.jaxb;

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

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

public class JAXBUnmarshalSample {

	public static void main(String[] args) {
		try {

			JAXBContext jaxbContext = JAXBContext
					.newInstance("com.javapapers.xml.jaxb");
			Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
			JAXBElement zoo = (JAXBElement) unmarshaller
					.unmarshal(new FileInputStream("zoo.xml"));
			ZooInfo zooInfo = (ZooInfo) zoo.getValue();

			System.out.println("Zoo Name: " + zooInfo.getZooName());
			System.out.println("Zoo Id: " + zooInfo.getZooId());

			Animals animals = zooInfo.getAnimals();
			List animalsList = animals.getAnimal();

			for (Animals.Animal animal : animalsList) {
				System.out.println("\t" + animal.getAnimalName());
				System.out.println("\t\t" + animal.getAnimalType());
			}

		} catch (JAXBException je) {
			je.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}
}

Output:

Zoo Name: Vandalur Zoo
Zoo Id: 12321
	Lion
		Wild
	Dog
		Domestic
	White Tiger
		Wild

JAXB Marshal Sample

After doing the above unmarshal we can use the same XSD and generated classes. Use the main method below to marshal.

package com.javapapers.xml.jaxb;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.List;

import javax.xml.bind.JAXB;
import javax.xml.bind.JAXBElement;

public class JAXBMarshalSample {

	public static void main(String[] args) throws FileNotFoundException {

		ZooInfo zoo = new ZooInfo();

		zoo.setZooId(987789);
		zoo.setZooName("Gir National Park");

		Animals animals = new Animals();

		List animalsList = animals.getAnimal();

		Animals.Animal animal1 = new Animals.Animal();
		animal1.setAnimalName("Jaguar");
		animal1.setAnimalType("Wild");

		Animals.Animal animal2 = new Animals.Animal();
		animal2.setAnimalName("Goat");
		animal2.setAnimalType("Domestic");

		Animals.Animal animal3 = new Animals.Animal();
		animal3.setAnimalName("Puma");
		animal3.setAnimalType("Wild");

		animalsList.add(animal1);
		animalsList.add(animal2);
		animalsList.add(animal3);

		zoo.setAnimals(animals);

		// create an element for marshalling
		JAXBElement zooInfoElement = (new ObjectFactory()).createZoo(zoo);

		// create a Marshaller and marshal to System.out
		JAXB.marshal(zooInfoElement, new FileOutputStream(new File("marshalledZoo.xml")));
	}
}

Download JAXBSample and Run

JAXB Advantages

  • JAXB is simple to use compared to SAX/DOM.
  • JAXB allows non-sequential processing of XML documents. In DOM we need to navigate a tree structure and JAXB doesn’t requires such navigations.
  • We work with java instances instead of event/elements.
    JAXB uses memory efficiently than DOM.
  • We can unmarshal XML data from different sources like InputStream object, a URL, a DOM node, or a transformed source object including a file.
  • Similarly we can marshal XMl content tree to different data targets.

Before closing some personal thoughts. I have written many starter articles touching subjects like Ajax, serialization, threading, web services, xml handling , java memory, design patterns and so on. When I take a subject I wish to write multiple articles on it covering major aspects of it. But it doesn’t happen always as I keep jumping between topics.

I have done well on covering design patterns. Java is like a ocean and every topic fascinates me and love to write on all those. Day by day javapapers is getting popular and we are adding new friends to the javapapers community. Added to appreciations I get lot of requests to write on certain topics.

Till now I have been predominantly writing on core java. This is to inform you friends I am planning to start writing Spring very soon and also expand to Hibernate and Android :-)

This JEE tutorial was added on 08/07/2012.

«

»

Comments on “JAXB Tutorial”

  1. Hello,

    Nice post. There are a couple of items I would like to comment on:

    1. The JAXB classes generated from an XML Schema are POJOs with the standard JAXB annotations. They are intended to be compatible with other JAXB implementations.

    2. An XML schema is not required to use JAXB. We designed JAXB to start from Java objects. JAXB is configuration by exception so you only need to add annotations to customize the mapping. The ability to generate a model from a XML Schema is offered as a convenience mechanism.

    -Blaise

    Blaise Doughan
    Team Lead, EclipseLink JAXB (MOXy)

    • Anonymous

      Respected Sir,

      I am working on Telugu Speech Recognition using Sphinx4 and Eclipse 3.4.0.

      Sir, I have some doughts, please kindly clarify me,

      1. The Demo Program of HelloWord is running successfully.

      2. In the HelloWorld java program there are words giving like,
      Good Morning,
      Biksha,
      Hello,
      Rita,
      Paul…etc.

      Here I wish to change these with Telugu words and the speech conversion must be in Telugu Language, please kindly help me.

  2. Joe

    Blaise,

    Thank you so much for the comments. I have updated the article with your words. Thanks.

    Regards,
    Joe.

  3. Gootam

    Good work Joe… Please keep it up

  4. Anonymous

    can u please wrtie some article with restful web service

  5. Rajper

    Really nice work.
    Efforts are appreciated.
    Carry on man.

  6. Anonymous

    Hi Joe…Would be so nice of you and really grateful to you if you please write
    “restful web service”

  7. Sandeep

    thank Joe .. good article to start with JAXB

  8. Najarhasan

    which jar file i can apply?what is the processor and which jre i can apply in class path because jre 1.6 class com.sun.tools.xjc.XJCTask is not found…plz needful rply

  9. Ashok

    Thanks Joe.
    Good job and keep it going.

  10. Joe

    @Najarhasan,

    You need JAXB implementation jar files. I am using Metro’s JAXB implementation and the jar files needed are, jaxb-xjc.jar and jaxb-impl.jar

    You can download these jars from, http://jaxb.java.net/2.2.5-2/ ->

    http://jaxb.java.net/2.2.5-2/JAXB2_20120516.jar

  11. Mayur

    Hi Joe,
    Thanks for such nice article. I find this blog really helpful for getting knowledge in java environment.

  12. Mayur Kumar

    Hi Joe,
    Thanks for such nice article. I find this blog really helpful for getting knowledge in java environment.

  13. sanjana

    God bless Mr.Joe. Thanks for sharing you knowledge…

  14. Uday

    Very nice Joe!

  15. Divya

    please provide the basics of hibernate,springs and structs framework

  16. Anguselvi

    Hi

    Initially I did the work in the same way. but now, I need to include schema in the xml file. Can you tell me how to do that.

  17. Hi Joe,

    Thank you wrote JAXB , this is very useful…good work …

  18. Gootam

    Hello Joe,
    can you please tell the difference between JAXB and Jibx?

    Thanks in Advance.
    Gootam.

  19. Ghost

    Isn’t it wiser to learn XStream this days if you have the choice?

  20. Bhushan

    I imported code and added required libs. Added POJO classes for Animal and ZooInfo
    but getting error for Animals.Animal cannot be resolved to type error.

    But I added Animals Animal ; field in Animals Class.. Please suggest.

  21. Bhushan

    I imported code and added required libs. Added POJO classes for Animal and ZooInfo
    but getting error for Animals.Animal cannot be resolved to type error.

    But I added Animals Animal ; field in Animals Class.. Please suggest.

  22. I always prefer ur articles when i try to understand something..Thanks for the valuable articles..

    Is there any better way to ignore namespace(xmlns) while converting xml to object conversion ???

  23. Gootam

    Hello Joe,

    Can you please tell the advantages of Jaxb over other technologies, like JIBX.

    Thanks.
    Gootam

  24. Nice one man…..Thanks a llot

  25. vasanth

    Hello joe,

    Thanks for good introduction about JAXB and your Sample Example easy to understand the JAXB Working flow and their API

    thanks a lot….

  26. ND

    Hi Joe,
    Great Post….Thanks a lot

    I’m facing a problem in xml parsing is that when I parse a xml the whitespace are eliminated, I want parse a xml without changes and write back it a file..

    is there any way,,

    Thanks ..

  27. Rathina

    Joe thanks … Mainly the JAXB using for converting XML to Java object or revers.
    But we need put annotation in pojo’s.
    If you possible provide that example also here. people can understand differents without using the XSD.

  28. Anonymous

    This is nice explanation on Jaxb but need same info regarding restful webservice..

    Thanks,
    Uday… :)

  29. sandeep shukla

    Thanks Joe !!! your blog in starting to become one stop shop for me to get started on new concepts . Thanks a lot

  30. Anonymous

    excellent example !!!!

  31. Prasad N

    Its a good article. Keep it up

  32. priya

    I am having a jrxml(jasper report) file which i want to convert to schema.
    Can you please help?

  33. gaurav goel

    Another great article sir.

  34. Anonymous

    your articles are just awesome…so simple yet cover every aspect….keep writing…you are doing a wonderful job…i am a great fan of yours.. :)

  35. Anonymous

    hello sir…i have a small doubt….there is a java API called “Long Term JavaBeans Persistence”, which is used to serialize java beans to xml files…what is the difference between LTJP and JAXB…is it so that the latter can be used to serialize Bean as well as Non-Bean classes…please help clear my confusion.

  36. SudharsanKss

    Cheers Joe.., Ur site Bookmarked .. Keep Going…!!!!

  37. siva

    Hi Joe,
    Great Post….Thanks a lot.

    i need in which scenarios we will use go for sax and jaxb.can u explain briefly.

    Thanks&Regards,
    siva

  38. Hello Sir,

    Can you please explain Spring example comparing
    with normal java code and how spring is loosely coupled.

    Rajpal Singh.

    • Anonymous

      Alright, Spring is based on concept of IOC. In IOC your implementing classes doesn’t depedent on the collaborating services directly rather it knows only abstraction. Service fetches its required dependencies when required.
      below is example:

      public class AnimalSimulator{
      private Animal animal;

      public void setAnimal(Animal animal) {
      this.animal = animal;

      }

      As you can see there is no way we have instantiated our animal object And our animal simulator knows only about animal . That animal can be dog, cat, rat….
      It comes to know those details only during runtime only through external configuration files(XML, java classes). Since the implementations can be swapped , It leads to loose coupling. AnimalSimulator knows any Animal through Animal class that’s all.

      Hope it helps!.

  39. Nitesh Gadekar

    nice work …..!
    keep it up

  40. Vidya

    I have very long, hundreds of or even thousands of records in my xml file. I want to parse the XML to java objects. I have planned to parse without using schema and annotate manualy.Is this a feasible way to do it or using schema to generate the POJOs is feasibledue to large number of fields in each record? pls suggest me on the same.

  41. Vidya

    Hi Joe..Very neat and clear work.Thanks alot.
    Keep up the gud wrk :)

  42. manju

    Good one…restful webservice, please

  43. Vishal

    Nice article !

    Java 1.6 also provides in built xjc command to convert XSD to java classes compatible with schema specified.

    Thanks,
    Vishal

  44. vijayakumar

    very nice explanations java papers is awesome :) thanks a lot

  45. arun kumar giri

    It is a nice example to understand JAXB parser.
    Thanks a lot to clarify my doubt.
    It is awesome.

  46. Raman

    can you tell me how to use JAXB and webservice combinely. I need to post the jaxb marshalled xml to a URL, the URL with soap envelop, now i need to put my jax-marshelled xml inside soap-env and send. can you help me

  47. Raju

    we are using jaxb moxy unmarshalling, and my java object has some logic in getter methods. so facing issue in unmarshalling, as the getter method is invoked twice by jaxb framework while unmarshalling. is there any way to avoid this getter method being called twice? any means we have in binding file to handle this? or can we have any wrapper on top of unmarshalling?

  48. TAM

    Hi joe you wrote very easily understood for others.Thanks

  49. tola odumosu

    can you please explain how one would unmarshal in a jax ws web service. i did but seems the soap envelop is formed before the jaxb unmarshalling gets called.

  50. Anonymous

    Hi Joe, This is very informative. Thank you.
    So is JAXB an alternative to JAXP or coming under JAXP family?

  51. kesav

    i want to get xml from java object, that would follow specific XSD. What i’m suppose to do.. PLZ help me.

  52. Telugu Movies

    Good work. Nice place for beginners to start. Thanks a lot.

  53. GURDEEP SINGH

    A Very good article on the usage of Jaxb.
    Thanks

  54. Sarthak Mishra

    Hi Joe,

    Thanks for this nice and easy to understand article.
    THe code you shared does not have all the required application classes (eg. ObjectFactory.java) etc. Could you please share those classes also. This will be very helpful for me to understand the topic fully.

    Thnks,

  55. Mohammed

    I am a fan of your tutorials

  56. Siddharth Das

    Nice article on JAXB..easy to understand..Thanks Joe.

  57. Nagendra

    Excellent tutorial

  58. Sarvesh

    Hi Jeo,
    While exectuing JAXBUnmarshalSample program, i’m getting below exception. Please help me out.

    javax.xml.bind.JAXBException: “com.javapapers.xml.jaxb” doesnt contain ObjectFactory.class or jaxb.index

  59. kishore

    Hi Joe,

    Once classes are generated for a given XSD can we change XSD to remove some of the elements with out regenerating classes, to generate XML by passing modified XSD

    Thanks

  60. ronnie

    Great and very helpful for dumb people like me.

  61. Bhaskar

    Respected Sir,

    I am working on Telugu Speech Recognition using Sphinx4 and Eclipse 3.4.0.

    Sir, I have some doughts, please kindly clarify me,

    1. The Demo Program of HelloWord is running successfully.

    2. In the HelloWorld java program there are words giving like,
    Good Morning,
    Biksha,
    Hello,
    Rita,
    Paul…etc.

    Here I wish to change these with Telugu words and the speech conversion must be in Telugu Language, please kindly help me.

  62. venkat

    how to use jaxb when the xml structure is not fixed and it might be of different structure each time

  63. venkat

    All i want to know is how to use jaxb for dynamic xml with out CDATA in it

  64. Seema

    In case I want to compare and merge 2 xml files, what could be the best way.

  65. Durga Prasad reddy

    nice article..

  66. Kumar

    Hi Joe,

    I want to achieve like following xml structures -

    Below are the expected xml construct that should be response of jersey restful
    service that will come from the POJO class.

    Problem Definition -

    class A is Having four properties i.e. hs, hs1, hs2, hs3
    class B is Having two properties of type class A;
    class c is having two properties of type class B;

    I am placing @xmlRootElement on each pojo class.

    Expected XML -

    currently I am getting error.

  67. Kumar

    Expected XML -

  68. Kumar

    Hi I am trying to post xml struxtures–

  69. Nagendra

    Joe,

    I have read many articles which you have written and all articles are very help full.

    I would like to know more about JAXB interns of

    when it is started?
    who started this (means implementer)?
    when it is completed the first version?
    also want to know the various versions released for JAXB with the release dates.

    I have to give a demo on this. So i am looking for these kind of information too.

    Thanks,
    Nagendra.

  70. Sofikul

    very helpful

  71. Ashwini

    Greatly explained

  72. Phil

    Thanks & Very useful info… Thanks for sharing it

  73. Balu

    Dear Sir,

    could you please let me know the url for the struts 2.0 tutorial
    Thanks
    Balu

  74. Aniruddh Sharma

    Hii Joe ,

    Really great work done by you but expecting article on RESTFULL web services and JERSEY framework from you .

  75. Raja

    I am getting
    xjc doesn’t support the destdir attribute

  76. M Naga Suresh

    I have attributes with space character as values. While marshalling, Marshaller trimming out the space characters. But I need those space characters to be preserved. How it can be acheived?

  77. avinash

    We are waiting for topics on Hibernate and appreciating your work.

  78. Rakesh

    Hi ,

    I am getting this com.sun.xml.bind.v2.runtime.JAXBContextImpl cannot be cast to com.sun.xml.internal.bind.api.JAXBRIContext

    error using jaxb And appserver was jboss 5.1.2.I have tried several blogs and souution none of them worked .
    Please help

  79. Object

    Nice article to start with!

    I have doubt on preventing XXE while unmarshalling using JAXB. All the googling results lead me to the same answer for avoiding XXE is to use an alternate SAX Parser and set security features to it.

    I would like to know if there is any way to configure secure features on the default parser mechanism used by JAXB. Also any way to identify the security features that comes by default with the JAXB parser.

    Thanks in Advance!

Your Comment