JAXB hello world example
JAXB, stands for Java Architecture for XML Binding, using JAXB annotation to convert Java object to / from XML file. In this tutorial, we show you how to use JAXB to do following stuffs :
- Marshalling – Convert a Java object into a XML file.
- Unmarshalling – Convert XML content into a Java Object.
Technologies used in this article
- JDK 1.6
- JAXB 2.0
Working with JAXB is easy, just annotate object with JAXB annotation, later use jaxbMarshaller.marshal() or jaxbMarshaller.unmarshal() to do the object / XML conversion.
1. JAXB Dependency
No extra jaxb libraries are required if you are using JDK1.6 or above, because JAXB is bundled in JDK 1.6.
For JDK < 1.6, download JAXB from here, and puts “jaxb-api.jar” and “jaxb-impl.jar” on your project classpath.
2. JAXB Annotation
For object that need to convert to / from XML file, it have to annotate with JAXB annotation. The annotation are pretty self-explanatory, you can refer to this JAXB guide for detail explanation.
package com.mkyong.core; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Customer { String name; int age; int id; public String getName() { return name; } @XmlElement public void setName(String name) { this.name = name; } public int getAge() { return age; } @XmlElement public void setAge(int age) { this.age = age; } public int getId() { return id; } @XmlAttribute public void setId(int id) { this.id = id; } }
3. Convert Object to XML
JAXB marshalling example, convert customer object into a XML file. The jaxbMarshaller.marshal() contains a lot of overloaded methods, find one that suit your output.
package com.mkyong.core; import java.io.File; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; public class JAXBExample { public static void main(String[] args) { Customer customer = new Customer(); customer.setId(100); customer.setName("mkyong"); customer.setAge(29); try { File file = new File("C:\\file.xml"); JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); // output pretty printed jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.marshal(customer, file); jaxbMarshaller.marshal(customer, System.out); } catch (JAXBException e) { e.printStackTrace(); } } }
Output
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <customer id="100"> <age>29</age> <name>mkyong</name> </customer>
4. Convert XML to Object
JAXB unmarshalling example, convert a XML file content into a customer object. The jaxbMarshaller.unmarshal() contains a lot of overloaded methods, find one that suit yours.
package com.mkyong.core; import java.io.File; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; public class JAXBExample { public static void main(String[] args) { try { File file = new File("C:\\file.xml"); JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file); System.out.println(customer); } catch (JAXBException e) { e.printStackTrace(); } } }
Output
Customer [name=mkyong, age=29, id=100]

hello,I am getting an error while running this code in eclipse.I have used jaxb.jar and jaxb.impl.jar but again the problem is same is there anything which i have to used for using this example
You forgot to define toString() method in your “Customer” class. Without this System.out.println(customer); will print something like “xxxxxxxxx.Customer@1a12fc0″ instead of “Customer [name=mkyong, age=29, id=100]“
Thank you for the concise example. The only issue I have is in the Object To Xml where the line:
jaxbMarshaller.marshal(customer, file);
has the error:
The method marshal(Object, Result) in the type Marshaller is not applicable for the arguments (Customer, File)
Please advise,
Ray
I have succesfully handled the error by using the following:
OutputStream os = new FileOutputStream(file);
jaxbMarshaller.marshal(customer, os);
Thank you again,
Ray
Hi Mkyong
It is very nice artical and very easy to understand.
But i have one problem in this,When i can run this application it will execute successfully and i am getting output also. But my source ‘XML’ file was not updated according to changes in the application.
Can u please help me any one !!!
Thanks
Hi Mkyong
It is very nice artical and very easy to understand.
But i have one problem in this,When i can run this application it will execute successfully and i am getting output also. But my source ‘XML’ file was not updated according to application.
Can u please help me any one !!!
Thanks
Hi,
What to do if i have to populate following xml file..
29
mkyong
i.e., two way hierarchy customers->customer->name, age will be the elements
That is because you have not overridden toString(). Add this
public String toString() {
return “Customer [name=" + name + ", age=" + age
+ ", id=" + id + "]“;
}
Override the toString() method in the Customer class.
thanx 4 d response
Hi mkyong.
Could you guide me on reading existing data from XML File in our JAXB classes. i.e data that was already stored in XML File before conversion into java classes.
hello I would like to use JAXB API 2.2 but it does not work with Android DALVIK it gives this error :
[2013-03-21 23:25:14 - AmazigheApps] Dx
trouble processing “javax/xml/bind/Binder.class”:
Ill-advised or mistaken usage of a core class (java.* or javax.*)
when not building a core library.
This is often due to inadvertently including a core library file
in your application’s project, when using an IDE (such as
Eclipse). If you are sure you’re not intentionally defining a
core class, then this is the most likely explanation of what’s
going on.
However, you might actually be trying to define a class in a core
namespace, the source of which you may have taken, for example,
from a non-Android virtual machine project. This will most
assuredly not work. At a minimum, it jeopardizes the
compatibility of your app with future versions of the platform.
It is also often of questionable legality.
If you really intend to build a core library — which is only
appropriate as part of creating a full virtual machine
distribution, as opposed to compiling an application — then use
the “–core-library” option to suppress this error message.
If you go ahead and use “–core-library” but are in fact
building an application, then be forewarned that your application
will still fail to build or run, at some point. Please be
prepared for angry customers who find, for example, that your
application ceases to function once they upgrade their operating
system. You will be to blame for this problem.
If you are legitimately using some code that happens to be in a
core package, then the easiest safe alternative you have is to
repackage that code. That is, move the classes in question into
your own package namespace. This means that they will never be in
conflict with core system classes. JarJar is a tool that may help
you in this endeavor. If you find that you cannot do this, then
that is an indication that the path you are on will ultimately
lead to pain, suffering, grief, and lamentation.
[2013-03-21 23:25:14 - AmazigheApps] Dx 1 error; aborting
[2013-03-21 23:25:14 - AmazigheApps] Conversion to Dalvik format failed with error 1
now I need the annotation JAXB 2.2 for Java object serialization with annotation
help me please !^^
Hi,
This is a great tutorial.
I am new to XML. I am confused on element vs. attributes. If I define an XML with elements (with say 5 levels of some nesting elements).. converting that to java will create too many Java Bean objects ? Will that be a performance issues ?
Or is it better to define attributes and make marshaling and marshaling easy ?
Are there any best practices with this respect ?
Thanks.
Deeps
Hi mkyong,
Can u please tell how to unmarshall the string response.
Good one with simple example. Some people explain too much but create confusion.
Things are simple and nice. Thanks.
Hi its a very nice tutorial..but when am trying to run the code it is throwing error
java.lang.UnsupportedClassVersionError: com/mkyong/core/JAXBExample : Unsupported major.minor version 51.0
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:620)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
at java.net.URLClassLoader.access$000(URLClassLoader.java:56)
at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
Hi Sumanc,
“java.lang.UnsupportedClassVersionError: com/mkyong/core/JAXBExample : Unsupported major.minor version 51.0″
usually indicates that you compile the source using a higher version of Java (e.g., Java 7) and run it with a lower version of Java (e.g., Java 6).
Just make sure that you compile the source and run it using the same Java version.
-vutbao
hi mkyong,
Nice explanation with good example.
Could you please give an example for marshalling multiple objects in to the same file?
In the above example how can i marshall two customer objects to the xml file?
Thanks for the tutorial.
Will try to leverage more of it!!
Can use JAXB in JDK 5
Thank you Very much for tutorial
MK? You are such a valued resource. Thank you so much for your examples, explanations and opening up comments and feedback for others to keep learning and sharing. Thank you! :)
superb…
but we need to add toString() method in Customer clas…
Thank you so much :)
Is there a way to use JAXB to unmarshal source XML to an existing object containing data (an object that i have previously instantiated and populated with data)? So when I call the unmarshal() method it merges/overwrites the data in the existing prepopluated object with data in the source XML? It effect, it updates the Java object with data in the source XML.
It appears I can only unmarshal to an new empty object that JAXB instantiates based on the class I pass in the newInstance() method.
hi
i am getting following exception when i run your code ,help is greatly appreciated
Exception in thread “main” javax.xml.bind.JAXBException
– with linked exception:
[java.lang.ClassNotFoundException: com.sun.xml.bind.v2.ContextFactory]
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:195)
at javax.xml.bind.ContextFinder.find(ContextFinder.java:381)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:574)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:522)
at Java2XML.main(Java2XML.java:22)
Caused by: java.lang.ClassNotFoundException: com.sun.xml.bind.v2.ContextFactory
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:191)
… 4 more
Java Result: 1
pls check if the jaxb-api.jar & jaxb-impl.jar is pointing to ur classpath or not.
Hi,
I noticed when using JAXB to generate XML for Objects with lists, that the generated List fields wasn’t proper javabean properties (since they lacked a setter method).
The setters’s methods are not generated.
Could you please, explain this ? Is it a JAXB Specification ?
Anyone ?
Best regards.
You access it via the getter as a live list. It is a bit odd.
blaablarvbalra rattegb nunar dreiay!
Hello this is a very nice tutorial!
Sir, How can i get the last Access date of a file in java6 ?
Hi Mayank,
My Requirement is little different. I am generating code for POJO (May have one to Many Many or One to One Mapping with other POJO classes also). But don’t want to generate the corresponding XML manually. Is there any way that I can generate the corresponding XML without having the Physical existance of the Class in the Project?
Hi Mkyoung,
could you please guide me to skip the “” value while marshaling?
Thanks,
BSK
I need to skip [xml version="1.0" encoding="UTF-8" standalone="yes"] this first tag.
Hi Mkyong,
Your note about compatibility of JAXB APIs with JDK1.5 helped me resolve a classnotFoundException for the same code I had written in JDK1.6.
Thanks a lot.
Hi,
I noticed when using JAXB to generate XML for Objects with lists, that the generated List fields wasn’t proper javabean properties (since they lacked a setter method).
The setters’s methods are not generated.
Could you please, explain this ? Is it a JAXB Specification ?
Best regards.
Great tutorial, thanks!
Hi mkyong,
I have requirement were i need to generate one xml file using defined XSD or DTD file using java. If its possible then please let me know how do i do this??
Your help will greatly appriciated.
Thanks,
Akshay
Hello Akshya
You can generate the Java classes based on XSD using JAXB. Once the classes are generated these can be used to generate the XML file by JAXB Marshaling.
Hope this helps
Vijya
Subbiah:
Hi Mkyong,
i cant understand in jaxb can you explain briefly, what is the usage of jaxb, how to use jaxb, what purpose to jaxb in my project, why used jaxb can you tel me
HI Mkyong,
I am a MSc CS Student, i am doing a course work on developing a web service using JAX WS using application server glassfish, i have been through all your tutorials it was pretty helpful.
my coursework is to utilise web services to compose a travel agency. The travel agency consists of three independent services: flight booking, hotel reservation, and currency conversion. i will build the first two application services by myself but i should consume a publically available service for currency conversion.
My issue is getting the flight information from java objects to xml document, my code is below
@WebMethod(operationName = “Flightfile”)
public Boolean CreateItinerary() {
//Create root XML node ‘ss’ and get its man element ‘newSegments’
Flights ss = new Flights();
List newSegments = (List) setSegments.getFlightSegments();
//Create Segments instanses and add them to the new Segments collection
ss toflights;
//Details about the Flight segments
toflights = new ss();
toflights.setAirline(“American Airlines”);
toflights.setOriginCity(“long beach”);
toflights.setDestinationCity(“aus islands”);
toflights.setAvailableSeats(“2″);
toflights.setPdestination(“short”);
//Details about the Fare price
Fare fk = new Fare();
toflights.setFareKey(fk);
toflights.getFareKey().setCurrency(“USD”);
toflights.getFareKey().setValue(120);
ss.add(toflights);
try {
javax.xml.bind.JAXBContext jaxbCtx = javax.xml.bind.JAXBContext.newInstance(ss.getClass().getPackage().getName());
javax.xml.bind.Marshaller marshaller = jaxbCtx.createMarshaller();
marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_ENCODING, “UTF-8″); //NOI18N
marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
//Writing to xml document
File flightstore = new File(“file.xml”);
marshaller.marshal(ss, flightstore);
} catch (javax.xml.bind.JAXBException ex) {
// XXXTODO Handle exception
java.util.logging.Logger.getLogger(“global”).log(java.util.logging.Level.SEVERE, null, ex); //NOI18N
}
———————————
This is my program for marshalling to xml file,
i have deployed the program, and tried to run it, web page opens but it is not writing the element info to xml file.
would you pls hlp me in this issue,
Thanks for your time.
Chao Fan,
Hi,
I noticed when using JAXB to generate XML for Objects with lists, that the generated List fields wasn’t proper javabean properties (since they lacked a setter method).
The setters’s methods are not generated.
Could you please, explain this ? Is it a JAXB Specification ?
Best regards.
P.S: this website rocks :)
Hi, at first great thanks for your help and patience.
I have a question that I have been facing for about two days, how can I marshal an existing xml rather than creating a new one? I mean, how can I create an xml and marshal using pagination.
Why I need to achieve this is because when I work with huge data sets I get out-of-memory exception at the db side. Therefore first I have get data using pagination from db, and immediately write them to xml then continue to get remaining data from db then so on..
Thanks for your help,
Cheers
Hello,
I think you can append the new marshalled string to previously marshalled xml string /file. Are you facing issues doing that?
StringWriter writer = new StringWriter();
marshaller.marshal(req, writer);
result = writer.toString();
Hello,
I am using the following method and actually I don’t know how to use StringWriter with my kind of approach as you see below.. Do you have any suggestions how can I reimplement the following with the code you mentioned? Thanks again.
Hello Mykong,
I am very new to xml parsing and jaxb. Executed your example and it helped a lot.
Thanks a lot for posting it.
But i need to understand a JAXB implementation with schema because i already have a xsd to which my xml will conform to.
Do you have any example showing this? or any link you can send to me.
Thanks.
Regards,
Naveen
You can use the xjc utility, using your xsd as an input. It will generate JAXB objects and a factory that you can use (or throw away) to access those objects.
Hello Folks,
I tried executing JAXB from eclipse using a schema file. Everything worked fine so far.
I have a few quick novice questions:
Is there any option to generate the JAXB classes from the schema using xsd. I did it by compiling the schema from the command prompt using xjc -p
Could any one help me how to understand the generated classes.
Hi Mkyong,
The same above example when i am Unmarshalling output getting like “Customer@c44b88″ this in myeclipse 8.5.
But the output is “Customer [name=mkyong, age=29, id=100]” what you have given above.
Could you please help me on this?
Thanks,
SatyamReddy K,
To get that output, you can just add a toString method to your Customer class, something like…
Hi MkYong,
I have a problem with Object Marshalling.
My scenario like as below.
I have created one xml like below
27
sada
flotNumaber
streetName
city
district
state
0
flotNumaber
streetName
city
district
state
0
Unmarshalling giving currect object.
If am trying to do marshalling the generated xml like
city
district
xyzs
0
state
streetName
city
district
xyzs
0
state
streetName
27
sada
You can observe the both the xml format and few elements are sorted as per ascending.
Could you please help me on this?
Thanks,
Sada. B
Hi Mkyong,
Another thing to point out about JAXB is that since it is a specification (JSR-222), there are multiple implementations: Metro, EclipseLink JAXB (MOXy), Apache JaxMe, etc.
For an example of specifying another JAXB provider see:
- http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html
-Blaise
Thanks for your comment, i learn something new :)
For single-time use JAXB has a handy facade.
and
Thanks for your additional inputs.
Hi Mkyong
It is very nice artical and very easy to understand.
But i have one problem in this,When i can run this application it will execute successfully and i am getting output also. But my source ‘XML’ file was not updated according to application.
Can u please help me any one !!!
Thanks