JAXB Tutorial

Last modified on October 11th, 2014 by Joe.

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.

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

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 :-)

Comments on "JAXB Tutorial"

  1. Blaise Doughan says:

    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)

  2. Joe says:

    Blaise,

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

    Regards,
    Joe.

  3. Gootam says:

    Good work Joe… Please keep it up

  4. Anonymous says:

    can u please wrtie some article with restful web service

  5. Rajper says:

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

  6. Anonymous says:

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

  7. Sandeep says:

    thank Joe .. good article to start with JAXB

  8. Najarhasan says:

    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 says:

    Thanks Joe.
    Good job and keep it going.

  10. Joe says:

    @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 says:

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

  12. Mayur Kumar says:

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

  13. sanjana says:

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

  14. Uday says:

    Very nice Joe!

  15. Divya says:

    please provide the basics of hibernate,springs and structs framework

  16. Anguselvi says:

    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. shiva says:

    Hi Joe,

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

  18. Gootam says:

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

    Thanks in Advance.
    Gootam.

  19. Ghost says:

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

  20. Bhushan says:

    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 says:

    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. Karthikeyan says:

    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 says:

    Hello Joe,

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

    Thanks.
    Gootam

  24. jAKEER says:

    Nice one man…..Thanks a llot

  25. vasanth says:

    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 says:

    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 says:

    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 says:

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

    Thanks,
    Uday… :)

  29. sandeep shukla says:

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

  30. nick says:

    good work

  31. Anonymous says:

    excellent example !!!!

  32. Prasad N says:

    Its a good article. Keep it up

  33. priya says:

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

  34. gaurav goel says:

    Another great article sir.

  35. Anonymous says:

    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.. :)

  36. Anonymous says:

    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.

  37. SudharsanKss says:

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

  38. siva says:

    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

  39. Rajpal Singh says:

    Hello Sir,

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

    Rajpal Singh.

  40. Nitesh Gadekar says:

    nice work …..!
    keep it up

  41. Vidya says:

    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.

  42. Vidya says:

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

  43. Anonymous says:

    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!.

  44. manju says:

    Good one…restful webservice, please

  45. Vishal says:

    Nice article !

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

    Thanks,
    Vishal

  46. vijayakumar says:

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

  47. arun kumar giri says:

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

  48. Raman says:

    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

  49. Raju says:

    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?

  50. TAM says:

    Hi joe you wrote very easily understood for others.Thanks

  51. tola odumosu says:

    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.

  52. Anonymous says:

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

  53. kesav says:

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

  54. Telugu Movies says:

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

  55. GURDEEP SINGH says:

    A Very good article on the usage of Jaxb.
    Thanks

  56. Sarthak Mishra says:

    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,

  57. Mohammed says:

    I am a fan of your tutorials

  58. Siddharth Das says:

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

  59. Nagendra says:

    Excellent tutorial

  60. Sarvesh says:

    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

  61. kishore says:

    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

  62. Anonymous says:

    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.

  63. ronnie says:

    Great and very helpful for dumb people like me.

  64. Bhaskar says:

    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.

  65. venkat says:

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

  66. venkat says:

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

  67. Seema says:

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

  68. Durga Prasad reddy says:

    nice article..

  69. Kumar says:

    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.

  70. Kumar says:

    Expected XML –

  71. Kumar says:

    Hi I am trying to post xml struxtures–

  72. Nagendra says:

    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.

  73. Sofikul says:

    very helpful

  74. Ashwini says:

    Greatly explained

  75. Phil says:

    Thanks & Very useful info… Thanks for sharing it

  76. Joe says:

    Welcome Phil.

  77. Balu says:

    Dear Sir,

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

  78. Aniruddh Sharma says:

    Hii Joe ,

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

  79. Raja says:

    I am getting
    xjc doesn’t support the destdir attribute

  80. M Naga Suresh says:

    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?

  81. avinash says:

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

  82. Rakesh says:

    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

  83. Object says:

    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!

Comments are closed for "JAXB Tutorial".