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

Student.java

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;

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

Marshall_Example.java

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();
        st.setName("JavaInterviewPoint");
        st.setAge("11");
        st.setId(12);
        try 
        {
            //Create jaxbContext
            JAXBContext jaxbContext = JAXBContext.newInstance(Student.class);
            //Getting Marshaller object
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
            //For Prettyprinted output
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);
            //Writing onto the file "Student.xml"
            jaxbMarshaller.marshal(st, new File("D:\\JIP\\Student.xml"));
            //Writing in the console
            jaxbMarshaller.marshal(st,System.out);
            
        } catch (JAXBException e) 
        {
            e.printStackTrace();
        }
    }
}

Output :

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  <student>
    <age>11</age>
    <id>12</id>
    <name>JavaInterviewPoint</name>
  </student>

Leave a Reply

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