JAXB Marshalling Example – Convert Java Object to XML in Java

In this example, we will see how we can convert a Java Object into an XML using JAXB Marshalling Technique.

JAXB Dependency

We will be requiring the below two jars to be put in the classpath for performing the marshalling operation.

  1. jaxb-api.jar
  2. jaxb-impl.jar


Our Student class is a simple POJO class containing three properties name,age,id. We will be using 2 main annotations namely @XmlRootElement(Maps Class to XML element) and @XmlElement(Maps Bean property to XML element).

package com.javainterviewpoint.jaxb;

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

public class Student 
    String name;
    String age;
    int id;
    public String getName() {
        return name;
    public void setName(String name) {
        this.name = name;
    public String getAge() {
        return age;
    public void setAge(String age) {
        this.age = age;
    public int getId() {
        return id;
    public void setId(int id) {
        this.id = id;


We will be performing the below steps to convert Object into XML

  • Create an object for our Student class and set values to the property associated with it.
  • JaxbContext is created by passing the class reference of the student class.
  • Call the createMarshaller() method of the context above created, to get the object of the Marshaller.
  • marshal() method is called which converts the Student object into an XML.
package com.javainterviewpoint.jaxb;

import java.io.File;

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

public class Marshal_Example 
    public static void main(String args[])
        Student st = new Student();
            //Create jaxbContext
            JAXBContext jaxbContext = JAXBContext.newInstance(Student.class);
            //Getting Marshaller object
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
            //For Prettyprinted output
            //Writing onto the file "Student.xml"
            jaxbMarshaller.marshal(st, new File("D:\\JIP\\Student.xml"));
            //Writing in the console
        } catch (JAXBException e) 

Output :

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

Leave a Reply

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