DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Migrate Serialized Java Objects with XStream and XMT
  • What Is Ant, Really?
  • How to Convert XLS to XLSX in Java
  • Writing DTOs With Java8, Lombok, and Java14+

Trending

  • The AI Autonomy Spectrum: 7 Architecture Patterns for Intelligent Applications
  • If You Can Survive a Toddler, You Can Ship LLMs in Production
  • Deployment Lessons You Only Learn the Hard Way
  • Logging What AI Agents Do in Salesforce: A Simple One-Object Audit Framework
  1. DZone
  2. Coding
  3. Languages
  4. Parse XML to Java Objects Using Jackson

Parse XML to Java Objects Using Jackson

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

By 
Srinivas Giduthuri user avatar
Srinivas Giduthuri
·
Sep. 20, 16 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
88.4K Views

Join the DZone community and get the full member experience.

Join For Free

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.9.6</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();
        // Reads from XML and converts to POJO
        Employees employees = objectMapper.readValue(
                StringUtils.toEncodedString(Files.readAllBytes(Paths.get("/tmp/employees.xml")), StandardCharsets.UTF_8),
                Employees.class);
        System.out.println(employees);
        // Reads from POJO and converts to XML
        objectMapper.writeValue(new File("/tmp/fieldsets.xml"), fieldSet);
    }
}


XML Object (computer science) Jackson (API) Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Migrate Serialized Java Objects with XStream and XMT
  • What Is Ant, Really?
  • How to Convert XLS to XLSX in Java
  • Writing DTOs With Java8, Lombok, and Java14+

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook