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, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
99 Comment threads
45 Thread replies
1 Followers
 
Most reacted comment
Hottest comment thread
119 Comment authors
Somanath BeheraJackRoseHamidehhpm 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 + “]”;
}

Jack
Guest
Jack

Multiple markers at this line
– Syntax error on token “Invalid Character”, delete
this token
– Syntax error on tokens, delete these tokens
– Syntax error on token “Invalid Character”, delete
this token
– Syntax error on tokens, delete these tokens
– Syntax error, insert “;” to complete BlockStatements
– The operator + is undefined for the argument
type(s) String

Malu
Guest
Malu

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

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

Hamideh
Guest
Hamideh

I get the same error when trying to use JAXB in Android. Were you able to use it in Android?

Zara Hussain
Guest
Zara Hussain

can you please say to parse without annotation

Chin
Guest
Chin

Vey clear explanation

zahra khoobi
Guest
zahra khoobi

I cant find that .jar file in like of jaxb in git project
Could you help me? and tell where should i find them?

Patricio Zambrano Garcia
Guest
Patricio Zambrano Garcia

Use maven and add dependecies to it

pdee
Guest
pdee

Simple and on point, thanks!

preeti sharma
Guest
preeti sharma

Do we need to maintain sequence for this?
Can i apply annotation on getter method also? Does it have different-different impact to apply on getter, setter or property itself?

private String key;
private String value;

@XmlElement(name=”Value”)
public String getValue()
{
return value;
}

@XmlElement(name=”Key”)
public String getKey()
{
return key;
}
public void setValue(String value) {
this.value= value;
}
public void setKey(String key) {
this.key= key;
}

IngenieRock Uriel Monzon
Guest
IngenieRock Uriel Monzon

Can covert OBJECT in XSD (Xml Schema Desc.)?

Priya
Guest
Priya

hii, how can we do this when we want to use it for 2 classes, example Customer class and Orders Class, my xml should have 2 tags like

….

PhanVu HoaiNam
Guest
PhanVu HoaiNam

Thank you very much.

prabhu v
Guest
prabhu v

pls anyone help me …how to add tostring in customer class

Karan Mhetre
Guest
Karan Mhetre

Please add below method in your Customer class :

public String toString(){

return “Customer [name=” + name + “, age=” + age + “, id=” + id +”]”;

}

prabhu v
Guest
prabhu v

PLs tel how to add tostring() in customer class

Pandari Ch
Guest
Pandari Ch

This is how we can Override toString method
public String toString() {
return “Customer [name=” + name+ “, age=” + age
+ “, id=” + id+ “]”;
}

Fred
Guest
Fred

@Override

public String toString(){

return(“Customer [name=” + this.getName() + “, age=” + this.getAge() + “, id=” + this.getId() +”]”);

}

Mitesh Jain
Guest
Mitesh Jain

I am getting java.lang.NoClassDefFoundError: com/ibm/xtq/bcel/util/BCELifier exception. What am i doing wrong?

Ramana
Guest
Ramana

facing same issue

Micheal Adenibuyan
Guest
Micheal Adenibuyan

Hi, Can you kindly assist me with this. I need to send an xml like this </paymentInfo

my challenge is the attributes representation.

Mateen
Guest
Mateen

In reading example the output is a hashcode, so please add the toString() method implementation in the Customer class to avoid misunderstandings :) .

Srihari
Guest
Srihari

I’m getting null pointer exception.
This is my xml file:

ID Issue Date must be equal or less than present date and greater than Date of BirthErrIsud0102000000003918246

this is my pojo class

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = “CARDUPDATE_RET”, propOrder = {“ResErrorMsg”,”ResErrorCode”,”ResCode”,”AccountNumber”})
public class CARDUPDATE_RET {
@XmlAttribute
private String xmlns=”http://www.corecard.com/Prepaid”;
@XmlElement(name = “AccountNumber”)
private String AccountNumber;
@XmlElement(name = “ResCode”)
private String ResCode;
@XmlElement(name = “ResErrorCode”)
private String ResErrorCode;
@XmlElement(name = “ResErrorMsg”)
private String ResErrorMsg;
//Setters and Getters
}
this my code
File file = new File(“D:/var/lib/tomcat7/webapps/tmpFiles/1.xml”);
JAXBContext jaxbContext = JAXBContext.newInstance(FVCardUpdateResponse.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
FVCardUpdateResponse CARDUPDATE_ret = (FVCardUpdateResponse) jaxbUnmarshaller.unmarshal(file);
System.out.println(“xml unmarshelled = “+CARDUPDATE_ret.getCARDUPDATE_RET().getResErrorMsg());

Srihari
Guest
Srihari

Hi. I’m calling a soap service like this StreamSource request = new StreamSource(new StringReader(requestedXML)); StringResult response=new StringResult(); webServiceTemplate.sendSourceAndReceiveToResult( “https://www.firstviewcorp.com/dbbapplications/ServicesSS/Selfservice.asmx”, request, // new SoapActionCallback(“http://networksolutions.com/ReadOrder”), actionCallBack, response); Now how can i assign this response to my java class?

Nilesh
Guest
Nilesh

awesome artical

Maurizio Perruolo
Guest
Maurizio Perruolo

Hi. I want to put a DOCTYPE to begin of file. Example

I want to cut the standalone=”yes” of the header.

Please help me thanks

Prateek Ashtikar
Guest
Prateek Ashtikar

Note – Either to annotate all fields or all getter methods in your Entity bean. A mix of both is not supported.
@XmlAccessorType(XmlAccessType.FIELD) at the class level if you want to annotate private fields instead of getter methods.

Hope this will be help. Thanks!!

mallikarjun reddy
Guest
mallikarjun reddy

Hi,
Nice article. It helps a lot. But ow we can handle multiple Customer objects to XML file.
Example, i want to generate the xml file as shown below, how to handle in this case?

29
mkyong

30
Ray

31
John

Semyon Evgrafov
Guest
Semyon Evgrafov

Hi, did you find you question answer out?

asdasd
Guest
asdasd

i cant find answer:-(

hpm
Guest
hpm

in that case you have to create customers class in that add list of customer class and then add for loop while adding and retrieving

pelao
Guest
pelao

nice

Priya
Guest
Priya

How to use this without eclipse or other IDE?

I copied the above example and have java 1.5 and downloaded jaxb-api.jar and jaxb-impl.jar in the lib folder and run this command
javac -classpath “.;lib” srccommkyongcoreJAXBExample.java

But I get errors like,

srccommkyongcoreJAXBExample.java:7: package javax.xml.bind does not exist
import javax.xml.bind.JAXBContext;
srccommkyongcoreJAXBExample.java:8: package javax.xml.bind does not exist
import javax.xml.bind.JAXBException;

How to get past these errors?

thomas
Guest
thomas

Thank you. Finally my code work.

Glauco Márdano
Guest
Glauco Márdano

Many thanks, I’ve never used JAXB before, it seems pretty cool.

vini
Guest
vini

NIce example mkyoung thanks

Subrat
Guest
Subrat

This is a good example but it will be better if you explain about each important statements.

John
Guest
John

he just copy it from a chinees site he dont understand anything

Denis Boiron
Guest
Denis Boiron

Savage

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

vb
Guest
vb

overwrite the toString() method in customer class

Amzi
Guest
Amzi

Thanks for your toString answer

prabhu v
Guest
prabhu v

can you pls share that code . i dont know how to add tostring in customer class

samridhi
Guest
samridhi

the jvm is giving u the hashcode of the object created.

Saurabh Porwal
Guest
Saurabh Porwal

override toString method in customer class

@Override

public String toString() {

return “Customer [name=” + name + “, age=” + age + “, id=” + id + “]”;

}

Tom
Guest
Tom

I am trying to print the element values and node names as your shoing in the program but i am not able to print just with System.out.println statement, Could you please help me how to print this?