JAXB Marshaller Example

The JAXB Marshaller interface is responsible for governing the process of serializing Java content trees i.e. Java objects to XML data. This marshalling to XML can be done to variety of output targets.

1. JAXB Marshalling Object to XML

1.1. Creating Marshaller

Generally, to create marshaller you can reuse this code.

JAXBContext jaxbContext 	= JAXBContext.newInstance( Employee.class );
Marshaller jaxbMarshaller 	= jaxbContext.createMarshaller();

Employee employeeObj = new Employee(1, "Lokesh", "Gupta", new Department(101, "IT"));

//Overloaded methods to marshal to different outputs

1.2. Marshal to XML File

OutputStream os = new FileOutputStream( "employee.xml" );
jaxbMarshaller.marshal( employeeObj, os );

1.3. Marshal to SAX ContentHandler

Assume MyContentHandler is instance of org.xml.sax.ContentHandler.

jaxbMarshaller.marshal( employeeObj, new MyContentHandler() );

1.4. Marshal to DOM Document

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.newDocument();

jaxbMarshaller.marshal( employeeObj, doc );

1.5. Marshal and print to console

m.marshal( employeeObj, new PrintWriter( System.out ) );

2. JAXB Marshaller Properties

jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
jaxbMarshaller.setProperty("jaxb.formatted.output", Boolean.TRUE);

All JAXB Providers are required to support the following set of properties. Some providers may support additional properties.

  • jaxb.encoding – The output encoding to use when marshalling the XML data. The Marshaller will use “UTF-8” by default if this property is not specified.
  • jaxb.formatted.output – Value can be true or false. Whether or not the Marshaller will format the resulting XML data with line breaks and indentation. Default value is false.
  • jaxb.schemaLocation – It allows the client application to specify an xsi:schemaLocation attribute in the generated XML data.
  • jaxb.noNamespaceSchemaLocation – It allows the client application to specify an xsi:noNamespaceSchemaLocation attribute in the generated XML data.
  • jaxb.fragment – It determines whether or not document level events will be generated by the Marshaller. Value can be true or false.

3. Marshaller Callback Methods

You can customize the marshalling operation by inside JAXB annotated class e.g. Employee.java. You need to define two methods which will listen before and after the marshaller process that class. In these methods, you can perform actions such as setting extra fields

package com.howtodoinjava.demo.model;

import java.io.Serializable;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "employee")
public class Employee implements Serializable {

	private static final long serialVersionUID = 1L;

	private Integer id;
	private String firstName;
	private String lastName;
	private Department department;

	public Employee() {

	//Setters and Getters

	public String toString() {
		return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", department="
				+ department + "]";

	// Invoked by Marshaller after it has created an instance of this object.
	boolean beforeMarshal(Marshaller marshaller) {
		System.out.println("Before Marshaller Callback");
		return true;

	// Invoked by Marshaller after it has marshalled all properties of this object.
	void afterMarshal(Marshaller marshaller) {
		System.out.println("After Marshaller Callback");

4. JAXB Marshalling Example

Example of marshalling Java Object to XML String.

package com.howtodoinjava.demo;

import java.io.StringWriter;

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

import com.howtodoinjava.demo.model.Department;
import com.howtodoinjava.demo.model.Employee;

public class JaxbExample 
	public static void main(String[] args) 
		Employee employee = new Employee(1, "Lokesh", "Gupta", new Department(101, "IT"));

	private static void jaxbObjectToXML(Employee employee) 
	    try {
	        JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class);
	        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

	        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // To format XML

	        //Print XML String to Console
	        jaxbMarshaller.marshal(employee, System.out);
	    } catch (JAXBException e) {

Program Output.

Before Marshaller Callback
After Marshaller Callback

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

Drop me your questions in comments section.

Happy Learning !!

Was this post helpful?

Join 8000+ Awesome Developers, Like YOU!

4 thoughts on “JAXB Marshaller Example”

Leave a Comment

About HowToDoInJava

This blog provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.