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;

@XmlRootElement
public class Employee {

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

    @XmlElement
    public String getFirstName() {
        return firstName;
    }

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

    @XmlElement
    public String getLastName() {
        return lastName;
    }

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

    @XmlElement
    public long getSsn() {
        return ssn;
    }

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

    @XmlAttribute
    public int geteId() {
        return eId;
    }

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

    @Override
    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">
    <firstName>James</firstName>
    <lastName>Bond</lastName>
    <ssn>123456789</ssn>
</employee>


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);
            System.out.println(employee);

        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }
}


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: