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 :

  1. Marshalling – Convert a Java object into a XML file.
  2. Unmarshalling – Convert XML content into a Java Object.

Technologies used in this article

  1. JDK 1.6
  2. 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.

Note
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]

References

  1. JAXB Official Website
  2. J2EE 5 JAXB tutorial

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
102 Comment threads
45 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
122 Comment authors
Rupak DeyEyad AymanDanSomanath BeheraJack Recent comment authors
newest oldest most voted
deadpool
Guest
deadpool

Add this method to “Customer” model class to get readable output.

@Override
public String toString() {
return “Customer [name=” + name + “, age=” + age + “, id=” + id + “]”;
}

Malu
Guest
Malu

I am using java8 and get the a warning restriction. For instance JAXBContext is not API. Do you know why?

Zara Hussain
Guest
Zara Hussain

can you please say to parse without annotation

Chin
Guest
Chin

Vey clear explanation

sagar
Guest
sagar

can i use this in android ??? i am getting this error while doing this in android. Javax.xml.bind.JAXBException – with linked exception: [java.lang.ClassNotFoundException: Didn’t find class “com.sun.xml.internal.bind.v2.ContextFactory” on path: DexPathList[[zip file “/data/app/com.uid-1/base.apk”],nativeLibraryDirectories=[/data/app/com.uid-1/lib/arm, /vendor/lib, /system/lib]]]

Peter
Guest
Peter

For single-time use JAXB has a handy facade.

JAXB.marshal(customer, new File("C:/file.xml"));

and

Customer customer = JAXB.unmarshall(new File("C:/file.xml"), Customer.class);
Alessandro Reis
Guest
Alessandro Reis

Nice article!

In the “Convert XML to Object” when it prints customer object I don’t see the same output you had. Do you have any idea?

You output:
Customer [name=mkyong, age=29, id=100]

My output:
examples.Customer@80d3d6f

trackback
Java XML Tutorial

[…] element and attribute.JAXB ExampleJAXB, using annotation to convert Java object to / from XML file.JAXB 2.0 hello world example A detail example to show you use JAXB to do XML Marshalling (convert object to XML) and XML […]

Blaise Doughan
Guest
Blaise Doughan

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

Sada
Guest
Sada

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

SatyamReddy
Guest
SatyamReddy

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,

venkat
Guest
venkat

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.

Naveen
Guest
Naveen

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

Canbaris
Guest
Canbaris

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

Mansour
Guest
Mansour

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 🙂

trackback
XML parsing of data java | PHP Developer Resource

[…] Here’s a really simple and quick intro to JAXB: http://www.mkyong.com/java/jaxb-hello-world-example/ […]

Chao Fan
Guest
Chao Fan

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… Read more »

Subbiah.g
Guest
Subbiah.g

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

Akshay
Guest
Akshay

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

Gary
Guest
Gary

Great tutorial, thanks!

Mansour
Guest
Mansour

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.

Rakesh
Guest
Rakesh

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.

baji
Guest
baji

Hi Mkyoung,

could you please guide me to skip the “” value while marshaling?

Thanks,
BSK

Krishnendu Sardar
Guest
Krishnendu Sardar

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?

sandeep.kumar
Guest
sandeep.kumar

Sir, How can i get the last Access date of a file in java6 ?

Marco
Guest
Marco

blaablarvbalra rattegb nunar dreiay!

Hello this is a very nice tutorial!

Mansour
Guest
Mansour

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.

divya
Guest
divya

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

alan
Guest
alan

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.

amro
Guest
amro

Thank you so much 🙂