January 2 2017

JAXB Unmarshaller Example

JAXB Unmarshaller Example

JAXB stands for Java Architecture for XML Binding. It provides mechanism to convert Java object to XML file (Marshalling) and XML file into a Java Object (Unmarshalling).

Unmarshalling

public interface Unmarshaller

The Unmarshaller class is responsible for converting XML data to Java Object.

Example

employee.xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee>
 <department>BSJ</department>
 <firstname>Amruth</firstname>
 <surname>M</surname>
 <uid>amruthm</uid>
</employee>

JAXB class – Employee.java

package com.answersz.jaxb;

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

@XmlRootElement
public class Employee {

 private String department;

 private String firstname;

 private String surname;

 private String uid;

 public String getDepartment() {
 return department;
 }

 @XmlElement
 public void setDepartment(String department) {
 this.department = department;
 }

 public String getFirstname() {
 return firstname;
 }

 @XmlElement
 public void setFirstname(String firstname) {
 this.firstname = firstname;
 }

 public String getSurname() {
 return surname;
 }

 @XmlElement
 public void setSurname(String surname) {
 this.surname = surname;
 }

 public String getUid() {
 return uid;
 }

 @XmlElement
 public void setUid(String uid) {
 this.uid = uid;
 }

}

JaxbMarshallerExample.java

package com.answersz.jaxb;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

public class JAXBUnmarshallerExample {

 public static void main(String[] args) {

 try {

 // JAXB Unmarshal Example

 // Xml file
 File file = new File("C:\\xml\\employee.xml");

 // Create the JAXBContext object
 JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class);

 // Create the Unmarshaller object
 Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

 // Unmarshalling from a File
 Employee employee = (Employee) jaxbUnmarshaller.unmarshal(file);

 System.out.println("First Name :" + employee.getFirstname());
 System.out.println("Sur Name :" + employee.getSurname());
 System.out.println("UID :" + employee.getUid());

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

Output

First Name :Amruth
Sur Name :M
UID :amruthm


Copyright © 2014. All rights reserved.

Posted January 2, 2017 by answersz in category JAXB

Leave a Comment

Your email address will not be published. Required fields are marked *

*