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.
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 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 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 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.
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(); ListanimalsList = 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
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(); ListanimalsList = 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"))); } }
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 are closed for "JAXB Tutorial".
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)
Blaise,
Thank you so much for the comments. I have updated the article with your words. Thanks.
Regards,
Joe.
Good work Joe… Please keep it up
can u please wrtie some article with restful web service
Really nice work.
Efforts are appreciated.
Carry on man.
Hi Joe…Would be so nice of you and really grateful to you if you please write
“restful web service”
thank Joe .. good article to start with JAXB
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
Thanks Joe.
Good job and keep it going.
@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
Hi Joe,
Thanks for such nice article. I find this blog really helpful for getting knowledge in java environment.
Hi Joe,
Thanks for such nice article. I find this blog really helpful for getting knowledge in java environment.
God bless Mr.Joe. Thanks for sharing you knowledge…
Very nice Joe!
please provide the basics of hibernate,springs and structs framework
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.
Hi Joe,
Thank you wrote JAXB , this is very useful…good work …
Hello Joe,
can you please tell the difference between JAXB and Jibx?
Thanks in Advance.
Gootam.
Isn’t it wiser to learn XStream this days if you have the choice?
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.
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.
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 ???
Hello Joe,
Can you please tell the advantages of Jaxb over other technologies, like JIBX.
Thanks.
Gootam
Nice one man…..Thanks a llot
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….
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 ..
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.
This is nice explanation on Jaxb but need same info regarding restful webservice..
Thanks,
Uday… :)
Thanks Joe !!! your blog in starting to become one stop shop for me to get started on new concepts . Thanks a lot
good work
excellent example !!!!
Its a good article. Keep it up
I am having a jrxml(jasper report) file which i want to convert to schema.
Can you please help?
Another great article sir.
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.. :)
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.
Cheers Joe.., Ur site Bookmarked .. Keep Going…!!!!
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
Hello Sir,
Can you please explain Spring example comparing
with normal java code and how spring is loosely coupled.
Rajpal Singh.
nice work …..!
keep it up
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.
Hi Joe..Very neat and clear work.Thanks alot.
Keep up the gud wrk :)
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!.
Good one…restful webservice, please
Nice article !
Java 1.6 also provides in built xjc command to convert XSD to java classes compatible with schema specified.
Thanks,
Vishal
very nice explanations java papers is awesome :) thanks a lot
It is a nice example to understand JAXB parser.
Thanks a lot to clarify my doubt.
It is awesome.
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
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?
Hi joe you wrote very easily understood for others.Thanks
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.
Hi Joe, This is very informative. Thank you.
So is JAXB an alternative to JAXP or coming under JAXP family?
i want to get xml from java object, that would follow specific XSD. What i’m suppose to do.. PLZ help me.
Good work. Nice place for beginners to start. Thanks a lot.
A Very good article on the usage of Jaxb.
Thanks
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,
I am a fan of your tutorials
Nice article on JAXB..easy to understand..Thanks Joe.
Excellent tutorial
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
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
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.
Great and very helpful for dumb people like me.
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.
how to use jaxb when the xml structure is not fixed and it might be of different structure each time
All i want to know is how to use jaxb for dynamic xml with out CDATA in it
In case I want to compare and merge 2 xml files, what could be the best way.
nice article..
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.
Expected XML –
Hi I am trying to post xml struxtures–
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.
very helpful
Greatly explained
Thanks & Very useful info… Thanks for sharing it
Welcome Phil.
Dear Sir,
could you please let me know the url for the struts 2.0 tutorial
Thanks
Balu
Hii Joe ,
Really great work done by you but expecting article on RESTFULL web services and JERSEY framework from you .
I am getting
xjc doesn’t support the destdir attribute
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?
We are waiting for topics on Hibernate and appreciating your work.
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
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!