We know that JAXB(Java Architecture for XML Binding) allows Java developers to map Java classes to XML representations. JAXB provides two main features: the ability to marshal Java objects into XML and the inverse, i.e. to unmarshal XML back into Java objects. JAXB mostly is used while implementing webservices or any other such client interface for an application where data needs to be transferred in XML format instead of HTML format which is default in case of visual client like web browsers.
A good example is facebook APIs. Facebook has exposed its services through some open endpoints in form of RESTful webservices where you hit a URL and post some parameters, and API return you the data in xml format. Now it is upto you, how you use that data.
In this post, I am giving an example to marshal and unmarshal the collection of objects. These collections in java can be of type : List
and Set
implementations e.g. ArrayList
or HashSet
.
1) JAXB Maven Dependencies
To run JAXB examples, we need to add run time maven dependencies like below:
<dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-core</artifactId> <version>2.2.8-b01</version> </dependency> <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-impl</artifactId> <version>2.2-promoted-b65</version> </dependency>
2) Model Classes
I have created a model class “Employee
” which has some common fields. I want to build code which could parse a set of employees
. Please note that JAXB requires @XmlRootElement
annotation on top most class which we are going to marshal or unmarshal.
ArrayList
class is part of collection framework and it does not have any JAXB annotations. So We need to have another class “Employees
” which will represent the set of employees. Now in this class we can add any annotation we like.
@XmlRootElement(name = "employee") @XmlAccessorType (XmlAccessType.FIELD) public class Employee { private Integer id; private String firstName; private String lastName; private double income; //Getters and Setters }
import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "employees") @XmlAccessorType (XmlAccessType.FIELD) public class Employees { @XmlElement(name = "employee") private List<Employee> employees = null; public List<Employee> getEmployees() { return employees; } public void setEmployees(List<Employee> employees) { this.employees = employees; } }
3) Marshal List to XML Example
Marshalling is “to convert the java object into xml representation”. In below example code, I am writing the list of employees
first in console, and then in a file.
//Initialize the employees list static Employees employees = new Employees(); static { employees.setEmployees(new ArrayList<Employee>()); //Create two employees Employee emp1 = new Employee(); emp1.setId(1); emp1.setFirstName("Lokesh"); emp1.setLastName("Gupta"); emp1.setIncome(100.0); Employee emp2 = new Employee(); emp2.setId(2); emp2.setFirstName("John"); emp2.setLastName("Mclane"); emp2.setIncome(200.0); //Add the employees in list employees.getEmployees().add(emp1); employees.getEmployees().add(emp2); } private static void marshalingExample() throws JAXBException { JAXBContext jaxbContext = JAXBContext.newInstance(Employees.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); //Marshal the employees list in console jaxbMarshaller.marshal(employees, System.out); //Marshal the employees list in file jaxbMarshaller.marshal(employees, new File("c:/temp/employees.xml")); }
Output of above code is :

4) Unmarshal XML to List Example
Unmarshalling is the process to convert xml back to java object. Let’s see the example of our Employees
class.
private static void unMarshalingExample() throws JAXBException { JAXBContext jaxbContext = JAXBContext.newInstance(Employees.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); //We had written this file in marshalling example Employees emps = (Employees) jaxbUnmarshaller.unmarshal( new File("c:/temp/employees.xml") ); for(Employee emp : emps.getEmployees()) { System.out.println(emp.getId()); System.out.println(emp.getFirstName()); } } Output: 1 Lokesh 2 John
5_ Sourcecode Download
To download the sourcecode of above example follow below link.
Happy Learning !!
Karen Jean Kramer
I have this exact problem but with the addition of this data being inside another root object which I can’t get to work.
Put your employees inside tags. How to you make a class called Company that will unMarshall the employees? I have success with the pattern that you gave, but this one last step returns null no matter how I try?
Harsh
Hello,
I am Creating three pojo classess(Details,Subscriber,Publisher).In Details class i am 2 creating list of subscriber type and publisher type.in Main Method i am creating their instance and adding in a list.But i am getting all the elements from each list together.But what i want is first element from subscriber and then publisher and then again 2nd element from subscriber and then publisher.Below are my Actual output and Expected Output
Lokesh Gupta
Interesting issue. I will try this in free time.
Svetoslav
This example is what I needed to build a xml file from an object. I was fighting with the ArrayList of objects setter for two evenings.
Thanks a lot
Saumya
Hi Lokesh,
Nice example. But i didn’t got one thing. If we want to display the id of the first employee only and nothing else Then how will you do it. Because here all the contents stored in the list is being displayed. If I want a single data stored in the List then how will i get it.
Lokesh Gupta
Then probably, you should be using xpath. JAXB will not be a good solution in this particular case.
Uma Maheswara Rao Marripudi
Hi Lokesh, Nice content. i need clarity. To convert java object to xml representation, we need have to JAXB.
Without JAXB is it possible? I am using spring restservices with JAXB.
Lokesh Gupta
No, JAXB is not required. You can use MOXy as well. Idea is that you need to use some interface which is capable of marshaling and unmarshalling.
OR, you can directly build your XML object and send in response.
I have one such example for JSON here: https://howtodoinjava.com/jersey/jax-rs-jersey-moxy-json-example/
You can use it for building XML by using https://jersey.github.io/
Uma Maheswara Rao Marripudi
So to convert java object to xml or json format we need other interfaces like JAXB or Jackson.
Other wise we can directly send our java object in the form of xml or json form as our wish.
Mostly we use JAXB and Jackson , am I correct Lokesh?
I have some confusion in web services while doing conversions like this. That’s why I am asking.
Lokesh Gupta
You are right.
Hemlata
When unmarshalling, is there a way to convert List types i.e. where
, into Arrays i.e.
instead of
.
I think it can be achieved by using a bindings file but I am not aware of the exact configuration to put in this file. Can you help?
Devender Singh
Hi Hemlata,
Did you get any solution for this Problem? Please revert if you had this sorted.
Jennifer
Hi, how can I run this without maven? I downloaded the three source files and try to compile and run with javac and java, it compiled ok, but got “could not find or load main class TestEmployeeMarshing” error when running. I used the same thing in STS and it worked fine? Can you help me? Thank you.
Lokesh Gupta
Add class files path in classpath parameter.
Zakaria
thank u for the article, didnt u forget to annotate the employee attributes with @XmlElement
id, firstName etc ?
Lokesh Gupta
When you use
@XmlAccessorType (XmlAccessType.FIELD)
at class, then@XmlElement
becomes optional.Javad
I want to have the Employees class to be a property of the Department class, so that the root node is the Department and the XML looks like:
How should I annotate the Department, The Employees, and the Employee classes to generate such an XML?
Himtie Liang
Many thanks! It really helps my work.
Rajat
Hi ,
I want to add a tostring method in the autogenerated class how can i do this
Lokesh Gupta
How you are generating the class? This
SA thread
has good information. Let me know if something else you want to know?PShukla
Thanks and it is a good basic tutorial !! 🙂
praveen
Can any one help me in detail how to extract the records from the belwo XML snippet
12
PRASAD56
Chennai
2014-10-20T00:00:00+05:30
pkk@gmail.co.in
2014-08-01T00:00:00+05:30
BSM_RESTeter
9916347942
9916347942
944990031
22
3
prasadk
10007896
18
PRASAD61
Chennai
2014-10-24T00:00:00+05:30
pkk@gmail.co.in
2014-08-01T00:00:00+05:30
BSM_RESTeter
9916347942
9916347942
9916347942
23
prasadk
10007896
1
1
2
12
Lokesh Gupta
Please read the message above in red to correctly post the code.
praveen
Hi lokesh ,I do not see any message in red
Lokesh Gupta
In comment box, please put your code inside [java] … [/java] OR [xml] … [/xml] tags otherwise it may not appear as intended. Tags are in small letters.
praveen
Hi Lokesh ,Below is my XML snippet.Please suggest a best way to extract the two records
Lokesh Gupta
Use jaxb with namespaces. An example could be: http://wiki.eclipse.org/EclipseLink/Release/2.4.0/JAXB_RI_Extensions/Namespace_Prefix_Mapper
You need to google more for this.
Ben
But in the unmarshalling example, you never defined getID() and getFirstName() so how would this work?
Lokesh Gupta
You see that I have written “//Getters and Setters”. Basically, I didn’t included them in example code here just to reduce the length of page.
shan
how to migrate my jaxb 1.0 classes to 2.0
Frostbite
There’s an existing program, where marshalling is included already. The problem is to unmarshal it. Whatever I try, it is not possible to unmarshal it. Can i send you a mail or something describing the problem?
Lokesh Gupta
Can you please elaborate more your problem. Please provide some error logs OR code in which you are facing the error.
Timothy
Suppose i have a list of employees withouth the wrapper tags i.e
…
…
How do i unmarshall it to a list/set ?
Lokesh Gupta
Please paste the code inside
[ java] ... [/java]
OR[ xml] ... [/xml]
tags.Timothy
Note i don’t have the outer employees tag
Lokesh Gupta
You must have any root element in XML. In above xml snippet, there is no root element.
Cesar
It’s great, thank you!
DK
thanks, very helpful example.
naveen
Hi. I have got some java files from an xsd file using jaxb xcj command line..now i have to convert them to an xml file..i came to know that using schemagen of jaxb it can be done..i tried but it is giving me an xsd file..what i want is xml equivalent of all those java files plz reply asap..
Lokesh Gupta
you need to use jaxb.
naveen
lokesh but im getting xsd file using that as i mentioned.what i want is an xml file
Lokesh Gupta
You can refer, what I mean, here in few examples: https://howtodoinjava.com/jaxb/jaxb-annotations/
OR//
Give me a sample class and sample XML what you want in output.
Roshan
Nice simple example. Helped me…
vinayak
how to Junit this unmarshal object?