How to Convert Object to XML using JAXB

In this tutorial, I am attaching the simple program about How to Convert Object to XML using JAXB.

Note: Typically the process of Object to XML conversion is called Marshalling.

We can able to Convert Object to XML using JAXB API`s. Which is part of Java SE. The below programs will give you idea about conversion of Object to XML.

The is normal POJO(Plain Old Java Object) class. Which has attributes, getters and setters accordingly. In order convert Object to XML we have to use @XmlRootElement annotation on top of the class. The following code will give you idea about @XmlRootElement annotation usage.

package com.dineshkrish.jaxb;

import javax.xml.bind.annotation.XmlRootElement;

public class Employee {

	private int employeeId;
	private String employeeName;
	private int employeeAge;
	private String employeeGender;
	private String employeeAddress;

	public int getemployeeId() {
		return employeeId;

	public void setemployeeId(int employeeId) {
		this.employeeId = employeeId;

	public String getemployeeName() {
		return employeeName;

	public void setemployeeName(String employeeName) {
		this.employeeName = employeeName;

	public int getemployeeAge() {
		return employeeAge;

	public void setemployeeAge(int employeeAge) {
		this.employeeAge = employeeAge;

	public String getemployeeGender() {
		return employeeGender;

	public void setemployeeGender(String employeeGender) {
		this.employeeGender = employeeGender;

	public String getemployeeAddress() {
		return employeeAddress;

	public void setemployeeAddress(String employeeAddress) {
		this.employeeAddress = employeeAddress;


The ObjectToXML class is responsible to convert Object to XML by using predefined classes such as JAXBContext and Marshaller. Which is belongs to javax.xml.bind package.

package com.dineshkrish.xml;


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

public class ObjectToXML {

	public static void main(String[] args) {
		Employee employee = new Employee();
		employee.setemployeeName("Dinesh Krishnan");
		File xmlFile = new File("employee.xml");
		try {
			JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class);
			Marshaller marshaller = jaxbContext.createMarshaller();
			marshaller.marshal(employee, xmlFile);
			System.out.println("Object Converted to XML...");
		} catch (JAXBException e) {


The generated XML file as show below.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
	<employeeName>Dinesh Krishnan</employeeName>



Object Converted to XML…


1. Java API Documentation

Hello everyone, I am a Founder of