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

  • Designing Frontend Applications for Failure, Not Just Success
  • Supercharging AI Agents with Azure Context: A Hands-On Guide to Azure MCP
  • MySQL Instant DDL: Metadata Locks, Waiting Writers, and Query Pileups
  • Beyond @Transactional: Solving the Dual-Write Problem in Distributed Microservices

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
·
Sep. 20, 16 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
88.6K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • 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