JAXB: Marshal / Unmarshal a List or Set

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

Comments

Subscribe
Notify of
guest
43 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

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.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode