JAXB Read XML to Java Object Example

Lokesh Gupta

Java examples to read a XML string or an XML file into a Java object (POJO). XML can be supplied by various means such as an XML file, a URL, or simply a string representation. The populated Java objects can then be used in the application for further processing or workflow.

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. JAXB vs. SAX vs. DOM Parsers

Java provides many approaches for reading an XML file and using the XL content to either print, use in an application, or populate data in Java objects to further use in the application lifecycle. The three main APIs used for this purpose are Simple API for XML (SAX), the Document Object Model (DOM) and Java Architecture for XML Binding (JAXB).

  • SAX or DOM parser uses the JAXP API to parse an XML document. Both scan the document and logically break it up into discrete pieces (e.g. nodes, text, comments etc).
  • SAX parser starts at the beginning of the document and passes each piece of the document to the application in the sequence it finds it. Nothing is saved in memory so it can’t do any in-memory manipulation.
  • DOM parser creates a tree of objects that represents the content and organization of data in the Document object in memory. Here, the application can then navigate through the tree to access the data it needs, and if appropriate, manipulate it.
  • While JAXB unmarshal the document into Java content objects. The Java content objects represent the content and organization of the XML document and are directly available to your program.

Read More: Read XML with SAX Parser and DOM Parser

3. Convert XML String to Java Object

To read XML, first get the JAXBContext. It is the entry point to the JAXB API and provides methods to unmarshal, marshal, and validate operations.

Now get the Unmarshaller instance from JAXBContext. It’s unmarshal() method unmarshal XML data from the specified XML and return the resulting content tree.

import com.howtodoinjava.xml.model.Employee;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Unmarshaller;
import java.io.StringReader;

public class ReadWriteXML {

  public static void main(String[] args) {

    // Convert XML String to Java Object

    String xmlString = "<employee>" +
        "    <department>" +
        "        <id>101</id>" +
        "        <name>IT</name>" +
        "    </department>" +
        "    <location>India</location>" +
        "    <firstName>Lokesh</firstName>" +
        "    <id>1</id>" +
        "    <lastName>Gupta</lastName>" +
        "</employee>";

    JAXBContext jaxbContext;
    try {
      jaxbContext = JAXBContext.newInstance(Employee.class);
      Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
      Employee employee = (Employee) jaxbUnmarshaller.unmarshal(new StringReader(xmlString));
      System.out.println(employee);
    } catch (JAXBException e) {
      e.printStackTrace();
    }

  }
}

4. Convert XML File to Java Object

Reading XML from a file is very similar to the above example. You only need to pass File object in place of StringReader object. File will have the reference to '.xml' file to be read in the file system.

File xmlFile = new File("employee.xml");
JAXBContext jaxbContext;

try {
  jaxbContext = JAXBContext.newInstance(Employee.class);        
  Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
  Employee employee = (Employee) jaxbUnmarshaller.unmarshal(xmlFile);
  System.out.println(employee);
} catch (JAXBException e) {
  e.printStackTrace();
}

5. Model

For reference purposes, we are using the following Employee and Department classes. Notice we have used the Jakarta annotations on the fields.

import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlRootElement;
import java.io.Serializable;

@XmlRootElement(name = "employee")
@XmlAccessorType(XmlAccessType.FIELD)
public class Employee implements Serializable {

  private static final long serialVersionUID = 1L;

  private Integer id;
  private String firstName;
  private String lastName;
  private String location;
  private Department department;

  // constructors, getters, setters, toString()
}
@XmlRootElement(name = "department")
@XmlAccessorType(XmlAccessType.FIELD)
public class Department implements Serializable {

  private static final long serialVersionUID = 1L;

  Integer id;
  String name;

  // constructors, getters, setters, toString()
}

Drop me your questions in the comments section.

Happy Learning !!

Source Code on Github

Comments

Subscribe
Notify of
guest
12 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.