JAXB example for Unmarshalling – Convert XML content into a Java Object.

First of all, let's get started with the java DTO with some fields and annotations we will complete the object.

package com.java.example;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

public class Employee {

    private String firstName;
    private String lastName;
    private long ssn;
    private int eId;

    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 long getSsn() {
        return ssn;

    public void setSsn(long ssn) {
        this.ssn = ssn;

    public int geteId() {
        return eId;

    public void seteId(int eId) {
        this.eId = eId;

    public String toString() {
        return "Employee [firstName=" + firstName + ", lastName=" + lastName
                + ", ssn=" + ssn + ", eId=" + eId + "]";

You can copy the employee.xml file to your C:\Temp\employee.xml and your file should look something like this.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee eId="7">

Now, let's write the core logic which will convert the xml into the java object. In new file object I've mentioned the location for the employee.xml file. Make sure you have the file at the same location with same content otherwise you may have to change the coding.

package com.java.example;

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

public class XmlToJava {

    public static void main(String[] args) {
        try {
            File file = new File("C:\\Temp\\employee.xml");
            JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class);

            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            Employee employee = (Employee) jaxbUnmarshaller.unmarshal(file);

        } catch (JAXBException e) {

Once after we run XmlToJava class we are going to get the following output into the console.

Employee [firstName=James, lastName=Bond, ssn=123456789, eId=7]

1 comment: