January 2 2017

JAXB Marshaller Example

JAXB Marshaller 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).


public interface Marshaller

The Marshaller class is responsible for converting Java object to XML data.


JAXB class – Employee.java

package com.answersz.jaxb;

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

public class Employee {

private String department;

private String firstname;

private String surname;

private String uid;

public String getDepartment() {
 return department;

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

public String getFirstname() {
 return firstname;

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

public String getSurname() {
 return surname;

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

public String getUid() {
 return uid;

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



package com.answersz.jaxb;

import java.io.File;

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

public class JaxbMarshallerExample {

 public static void main(String[] args) {

 try {

 // JAXB Marshaller Example

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

 // Create the Marshaller object
 Marshaller marshaller = jaxbContext.createMarshaller();

 // output pretty printed
 marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

 // Create file
 File file = new File("employee.xml");

 Employee employee = new Employee();

 // Marshal the content tree rooted at jaxbElement into a file
 marshaller.marshal(employee, file);

 } catch (JAXBException e) {


employee.xml (after running the above class)

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

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 *