JAXB: Marshal / Unmarshal a List or Set

Java examples to marshal and unmarshal the collection of objects of type List and Set implementations such as ArrayList or HashSet into XML.

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 = &quot;employee&quot;)
@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 :

JAXB marshalling example output
JAXB marshalling example output

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

Source Code on Github

Leave a Comment

  1. 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?

    Reply
  2. 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

    Actual Output
    ---------------------------------
    <Details>
      <Subscriber>
       <firstName></firstName>
       <Address></Adddress>
       <Mobile></Mobile>
      </Subscriber>
      <Subscriber>
       <firstName></firstName>
       <Address></Adddress>
       <Mobile></Mobile>
      </Subscriber>
      <Publisher>
       <BookName></BookName>
       <Price></Price>
      </Publisher>
      <Publisher>
       <BookName></BookName>
       <Price></Price>
      </Publisher>
    </Details>
    
    
    Expected Output
    ------------------------------
    <Details>
      <Subscriber>
       <firstName></firstName>
       <Address></Adddress>
       <Mobile></Mobile>
      </Subscriber>
      <Publisher>
       <BookName></BookName>
       <Price></Price>
      </Publisher>
      <Subscriber>
       <firstName></firstName>
       <Address></Adddress>
       <Mobile></Mobile>
      </Subscriber>
      <Publisher>
       <BookName></BookName>
       <Price></Price>
       </Publisher>
    </Details>
    
    
    Reply
  3. 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

    Reply
  4. 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.

    Reply
  5. 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.

    Reply
  6. When unmarshalling, is there a way to convert List types i.e. where

    <xs:element maxOccurs="unbounded" minOccurs="0" name="errorDataList" nillable="true" type="ErrorData"/>

    , into Arrays i.e.

    protected ErrorData[] errorDataList;

    instead of

    protected List<ErrorData> errorDataList

    .

    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?

    Reply
  7. 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.

    Reply
  8. 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?

    Reply
  9. 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

    Reply
          • Hi Lokesh ,Below is my XML snippet.Please suggest a best way to extract the two records

            
            <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
            <collection xmlns:sure="http://www.proj1.com/sure" xmlns:atom="http://www.w3.org/2005/Atom">
            <links/>
            <element xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="sure:customer">
            <atom:link rel="customer" href="http://172.19.112.145:8080/proj1/sure/customerFeatures/3/customer"/>
            <atom:link rel="self" href="http://172.19.112.145:8080/Proj1/sure/customerFeatures/3"/><atom:link rel="state" href="http://172.19.112.145:8080/Proj1/sure/customers/12/state"/>
            <atom:link rel="customerFeatures" href="http://172.19.112.145:8080/Proj1/sure/customers/12/customerFeatures"/>
            <atom:link rel="customerFeatures" href="http://172.19.112.145:8080/Proj1/sure/customers/12/customerFeatures"/>
            <atom:link rel="ipPool" href="http://172.19.112.145:8080/Proj1/sure/customers/12/ipPool"/>
            <atom:link rel="status" href="http://172.19.112.145:8080/Proj1/sure/customers/12/status"/>
            <atom:link rel="paths" href="http://172.19.112.145:8080/Proj1/sure/customers/12/paths"/>
            <sure:customerId>12</sure:customerId>
            <sure:customerName>PRASAD56</sure:customerName>
            <sure:address>Chennai</sure:address>
            <sure:creationDate>2014-10-20T00:00:00+05:30</sure:creationDate>
            <sure:email>pkk@gmail.co.in</sure:email>
            <sure:lastUpdate>2014-08-01T00:00:00+05:30</sure:lastUpdate>
            <sure:nameDetail>BSM_RESTeter</sure:nameDetail>
            <sure:phoneBiz>9916347942</sure:phoneBiz>
            <sure:phoneHome>9916347942</sure:phoneHome>
            <sure:phoneMobile>944990031</sure:phoneMobile>
            <sure:rating>22</sure:rating>
            <sure:customerFeature>
            <atom:link rel="customer" href="http://172.19.112.145:8080/Proj1/sure/customerFeatures/3/customer"/>
            <atom:link rel="self" href="http://172.19.112.145:8080/Proj1/sure/customerFeatures/3"/>
            <sure:customerFeatureId>3</sure:customerFeatureId>
            <sure:name>prasadk</sure:name>
            <sure:value>10007896</sure:value>
            </sure:customerFeature>
            </element>
            
            <element xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="sure:customer">
            <atom:link rel="services" href="http://172.19.112.145:8080/Proj1/sure/customers/18/services"/>
            <atom:link rel="self" href="http://172.19.112.145:8080/Proj1/sure/customers/18"/>
            <atom:link rel="state" href="http://172.19.112.145:8080/Proj1/sure/customers/18/state"/>
            <atom:link rel="customerFeatures" href="http://172.19.112.145:8080/Proj1/sure/customers/18/customerFeatures"/>
            <atom:link rel="customerFeatures" href="http://172.19.112.145:8080/Proj1/sure/customers/18/customerFeatures"/>
            <atom:link rel="ipPool" href="http://172.19.112.145:8080/Proj1/sure/customers/18/ipPool"/>
            <atom:link rel="status" href="http://172.19.112.145:8080/Proj1/sure/customers/18/status"/>
            <atom:link rel="paths" href="http://172.19.112.145:8080/Proj1/sure/customers/18/paths"/>
            <sure:customerId>18</sure:customerId>
            <sure:customerName>PRASAD61</sure:customerName>
            <sure:address>Chennai</sure:address>
            <sure:creationDate>2014-10-24T00:00:00+05:30</sure:creationDate>
            <sure:email>pkk@gmail.co.in</sure:email>
            <sure:lastUpdate>2014-08-01T00:00:00+05:30</sure:lastUpdate>
            <sure:nameDetail>BSM_RESTeter</sure:nameDetail>
            <sure:phoneBiz>9916347942</sure:phoneBiz>
            <sure:phoneHome>9916347942</sure:phoneHome>
            <sure:phoneMobile>9916347942</sure:phoneMobile>
            <sure:rating>23</sure:rating>
            <sure:customerFeature>
            <atom:link rel="customer" href="http://172.19.112.145:8080/Proj1/sure/customerFeatures/9/customer"/>
            <atom:link rel="self" href="http://172.19.112.145:8080/Proj1/sure/customerFeatures/9"/>
            <sure:customerFeatureId></sure:customerFeatureId>
            <sure:name>prasadk</sure:name>
            <sure:value>10007896</sure:value>
            </sure:customerFeature>
            </element>
            
             <metaData>
            <totalPages>1</totalPages>
            <currentPage>1</currentPage>
            <totalElements>2</totalElements>
            <limit>12</limit>
            </metaData>
            
            </collection>
            
  10. 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?

    Reply
  11. Suppose i have a list of employees withouth the wrapper tags i.e

    How do i unmarshall it to a list/set ?

    Reply
  12. 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..

    Reply

Leave a Comment

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.