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 the default in the case of visual clients like web browsers.
A good example is Facebook APIs. Facebook has exposed its services through some open endpoints in the form of RESTful webservices where you hit a URL and post some parameters, and the API returns 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. Maven
Start with adding the latest ‘jakarta‘ dependencies for adding the JAXB support (Java 11 onwards).
<dependencies>
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>4.0.0</version>
</dependency>
</dependencies>
<dependencies>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>4.0.3</version>
<scope>runtime</scope>
</dependency>
</dependencies>
2. Model Classes
I have created a model class “Employee” which has some common fields. I want to build code that could parse a set of employees. Please note that JAXB requires @XmlRootElement annotation on the topmost class which we are going to marshal or unmarshal.
ArrayList class is part of the 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, Setters. Constructors
}
@XmlRootElement(name = "employees")
@XmlAccessorType(XmlAccessType.FIELD)
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. Marshalling List to XML Example
Marshaling is “to convert the java object into xml representation“. In the below example code, I am writing the list of employees first in the console, and then in a file.
import com.howtodoinjava.xml.model.Employee;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Marshaller;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlRootElement;
public class MarshalListExample {
public static void main(String[] args) throws JAXBException {
Employees employees = new Employees();
//Add the employees in list
Employee emp1 = new Employee(1, "Lokesh", "Gupta", null, null);
Employee emp2 = new Employee(1, "John", "McLean", null, null);
employees.getEmployees().add(emp1);
employees.getEmployees().add(emp2);
//Write to XML
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("out.xml"));
}
}
Output of the 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.
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("out.xml"));
for (Employee emp : emps.getEmployees()) {
System.out.println(emp.getId());
System.out.println(emp.getFirstName());
}
Happy Learning !!
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?
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
Interesting issue. I will try this in free time.
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
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.
Then probably, you should be using xpath. JAXB will not be a good solution in this particular case.
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.
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/
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.
You are right.
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?
Hi Hemlata,
Did you get any solution for this Problem? Please revert if you had this sorted.
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.
Add class files path in classpath parameter.
thank u for the article, didnt u forget to annotate the employee attributes with @XmlElement
id, firstName etc ?
When you use
@XmlAccessorType (XmlAccessType.FIELD)at class, then@XmlElementbecomes optional.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?
Many thanks! It really helps my work.
Hi ,
I want to add a tostring method in the autogenerated class how can i do this
How you are generating the class? This
SA threadhas good information. Let me know if something else you want to know?Thanks and it is a good basic tutorial !! :)
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
Please read the message above in red to correctly post the code.
Hi lokesh ,I do not see any message in red
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.
Hi Lokesh ,Below is my XML snippet.Please suggest a best way to extract the two records
Use jaxb with namespaces. An example could be: Namespace_Prefix_Mapper
You need to google more for this.
But in the unmarshalling example, you never defined getID() and getFirstName() so how would this work?
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.
how to migrate my jaxb 1.0 classes to 2.0
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?
Can you please elaborate more your problem. Please provide some error logs OR code in which you are facing the error.
Suppose i have a list of employees withouth the wrapper tags i.e
…
…
How do i unmarshall it to a list/set ?
Please paste the code inside
[ java] ... [/java]OR[ xml] ... [/xml]tags.Note i don’t have the outer employees tag
You must have any root element in XML. In above xml snippet, there is no root element.
thanks, very helpful example.
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..
you need to use jaxb.
lokesh but im getting xsd file using that as i mentioned.what i want is an xml file
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.
Nice simple example. Helped me…
how to Junit this unmarshal object?