Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Parse XML to Java Objects Using Jackson

DZone's Guide to

Parse XML to Java Objects Using Jackson

Check out this short tutorial on how to parse XML to Java objects using Jackson.

· Web Dev Zone ·
Free Resource

Learn how error monitoring with Sentry closes the gap between the product team and your customers. With Sentry, you can focus on what you do best: building and scaling software that makes your users’ lives better.

Parsing the XML document to Java objects using Jackson library is quite simple. 

The following is the XML that we are going to parse.

<employees>
    <employee id="EMP0001">
        <first_name>John</first_name>
        <last_name>Doe</last_name>
        <age>26</age>
    </employee>
    <employee id="EMP0002">
        <first_name>Peter</first_name>
        <last_name>Parker</last_name>
        <age>30</age>
    </employee>
</employees>

To parse the above XML, we will use Jackson library. We have also included Apache Commons library for converting bytes to String. The maven dependency is as follows.

<dependency>
  <groupId>com.fasterxml.jackson.dataformat</groupId>
  <artifactId>jackson-dataformat-xml</artifactId>
  <version>2.6.3</version>
</dependency>
<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.4</version>
</dependency>

We need to create the model objects according to the XML. There will be two model objects.

Employees:

import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;

import java.util.Arrays;

@JacksonXmlRootElement(localName = "employees") public final class Employees {
    @JacksonXmlElementWrapper(localName = "employee", useWrapping = false)
    private Employee[] employee;

    public Employees() {
    }

    public Employees(Employee[] employee) {
        this.employee = employee;
    }

    public Employee[] getEmployee() {
        return employee;
    }

    public void setEmployee(Employee[] employee) {
        this.employee = employee;
    }

    @Override public String toString() {
        return "Employees{" +
                "employees=" + Arrays.toString(employee) +
                '}';
    }
}

Employee:

import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;

public final class Employee {
    @JacksonXmlProperty(localName = "id", isAttribute = true)
    private String id;
    @JacksonXmlProperty(localName = "first_name")
    private String firstName;
    @JacksonXmlProperty(localName = "last_name")
    private String lastName;
    @JacksonXmlProperty(localName = "age")
    private int age;

    public Employee() {
    }

    public Employee(String id, String firstName, String lastName, int age) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override public String toString() {
        return "Employee{" +
                "id='" + id + '\'' +
                ", firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                ", age=" + age +
                '}';
    }
}

There are few annotations that were added to the model objects which play a key role. They are JacksonXmlRootElement, JacksonXmlElementWrapper and JacksonXmlProperty.

The following is the code to parse the above XML document.

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

public class Parser {
    public static void main(String[] args) throws IOException {
        ObjectMapper objectMapper = new XmlMapper();
        Employees employees = objectMapper.readValue(
                StringUtils.toEncodedString(Files.readAllBytes(Paths.get("/tmp/employees.xml")), StandardCharsets.UTF_8),
                Employees.class);
        System.out.println(employees);
    }
}


What’s the best way to boost the efficiency of your product team and ship with confidence? Check out this ebook to learn how Sentry's real-time error monitoring helps developers stay in their workflow to fix bugs before the user even knows there’s a problem.

Topics:
jackson ,xml ,java

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}