JAXB Hello World Example

JAXB, stands for Java Architecture for XML Binding, using JAXB annotation to convert Java object to / from XML file. In this tutorial, we show you how to use JAXB to do following stuffs :

  • Marshalling – Convert a Java object into a XML file.
  • Unmarshalling – Convert XML content into a Java Object.

Technologies used in this article

  • JDK 1.6
  • JAXB 2.2.7

Working with JAXB is easy, just annotate object with JAXB annotation, later use jaxbMarshaller.marshal() or jaxbMarshaller.unmarshal() to do the object / XML conversion.

Simple JAXB Marshalling Example: Converting Object into XML

Let’s see the steps to convert java object into XML document.

  1. Create POJO or bind the schema and generate the classes
  2. Create the JAXBContext object
  3. Create the Marshaller objects
  4. Create the content tree by using set methods
  5. Call the marshal method


package com.doj.jaxb;

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

 * @author Dinesh Rajput
public class Employee {
 private int empid;  
    private String name;  
    private float salary;
    private String address;
    public int getEmpid() {
  return empid;
 public void setEmpid(int empid) {
  this.empid = empid;
 public String getName() {
  return name;
 public void setName(String name) {
  this.name = name;
 public float getSalary() {
  return salary;
 public void setSalary(float salary) {
  this.salary = salary;
 public String getAddress() {
  return address;
 public void setAddress(String address) {
  this.address = address;

  • @XmlRootElement specifies the root element for the xml document.
  • @XmlAttribute specifies the attribute for the root element.
  • @XmlElement specifies the sub element for the root element.

package com.doj.jaxb;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

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

 * @author Dinesh Rajput
public class ObjectToXMLTest {

  * @param args
  * @throws JAXBException 
  * @throws FileNotFoundException 
 public static void main(String[] args) throws JAXBException, FileNotFoundException {
  JAXBContext contextObj = JAXBContext.newInstance(Employee.class);  
     Marshaller marshallerObj = contextObj.createMarshaller();  
     marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);  
     Employee emp = new Employee();
     emp.setName("Dinesh Rajput");
     marshallerObj.marshal(emp, new FileOutputStream("employee.xml"));  


Run this application as java program lets see following output file in application

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee empid="1111">
    <name>Dinesh Rajput</name>

JAXB Hello World Example

Download Source Code with libs

<<Previous <<   || Index ||   >>Next >>