JAXB Write Java Object to XML Example

Java example to write Java object to XML. Information stored in Java objects fields can written into XML file or simply XML string as well.

1) Convert Java Object to XML String

To write Java object to XML String, first get the JAXBContext. It is entry point to the JAXB API and provides methods to unmarshal, marshal and validate operations.

Now get the Marshaller instance from JAXBContext. It’s marshal() method marshals Java object into XML. Now this XML can be written to different outputs e.g. string, file or stream.

package com.howtodoinjava.demo;

import java.io.File;
import java.io.StringWriter;

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

public class JaxbExample 
{
	public static void main(String[] args) 
	{
		//Java object. We will convert it to XML.
		Employee employee = new Employee(1, "Lokesh", "Gupta", new Department(101, "IT"));
		
		//Method which uses JAXB to convert object to XML
		jaxbObjectToXML(employee);
	}

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

	        //Required formatting??
	        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

	        //Print XML String to Console
	        StringWriter sw = new StringWriter();
	        
	        //Write XML to StringWriter
	        jaxbMarshaller.marshal(employee, sw);
	        
	        //Verify XML Content
	        String xmlContent = sw.toString();
	        System.out.println( xmlContent );

	    } catch (JAXBException e) {
	        e.printStackTrace();
	    }
	}
}

Program Output.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee>
    <department>
        <id>101</id>
        <name>IT</name>
    </department>
    <firstName>Lokesh</firstName>
    <id>1</id>
    <lastName>Gupta</lastName>
</employee>

2) Convert Java Object to XML File

Writing XML to file is very similar to above example. You only need to provide XML file location where you want to write the file.

package com.howtodoinjava.demo;

import java.io.File;
import java.io.StringWriter;

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

public class JaxbExample 
{
	public static void main(String[] args) 
	{
		//Java object. We will convert it to XML.
		Employee employee = new Employee(1, "Lokesh", "Gupta", new Department(101, "IT"));
		
		//Method which uses JAXB to convert object to XML
		jaxbObjectToXML(employee);
	}

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

	        //Required formatting??
	        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

	       //Store XML to File
	        File file = new File("employee.xml");
	        
	        //Writes XML file to file-system
	        jaxbMarshaller.marshal(employee, file);	
	    } 
	    catch (JAXBException e) 
	    {
	        e.printStackTrace();
	    }
	}
}

Program Output.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee>
    <department>
        <id>101</id>
        <name>IT</name>
    </department>
    <firstName>Lokesh</firstName>
    <id>1</id>
    <lastName>Gupta</lastName>
</employee>

3) Read XML Example

If you want to read the XML from file to Java object again, then use this method.

String fileName = "employee.xml";

//Call method which read the XML file above
jaxbXmlFileToObject(fileName);

private static void jaxbXmlFileToObject(String fileName) {
		
		File xmlFile = new File(fileName);
		
		JAXBContext jaxbContext;
		try 
		{
			jaxbContext = JAXBContext.newInstance(Employee.class);
			Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
			Employee employee = (Employee) jaxbUnmarshaller.unmarshal(xmlFile);
			
			System.out.println(employee);
		}
		catch (JAXBException e) 
		{
			e.printStackTrace();
		}
	}

Program Output.

Employee [id=1, firstName=Lokesh, lastName=Gupta, department=Department [id=101, name=IT]]

Drop me your questions in comments section.

Happy Learning !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

6 thoughts on “JAXB Write Java Object to XML Example”

  1. We have output of one XML file in one object using JAXB.
    We want to export the same java object to another XML format with different XML tags.
    Basically we want to map one XML to another XML file.
    How can we do this ?
    Is there any other way to this other that JAXB

    Reply
  2. Excellent work Lokesh!!
    I had a question,
    Say I have schema(xsd) and i converted that into pojos’ using xjc.
    Now I am converting those into xml.
    question here is if certain elements have minOccurs=0 in schema
    how they are handled in generating xml using the pojos?
    if the data is not there and when i add/set those classes I get empty xml tags.
    How can I avoid getting empty xml tags?

    Thanks for your help in advance

    Reply
  3. hello… I was trying to use arraylist for mashalling and unmarshalling.. the marshalling process went smoothly however the unmarshalling printed weird output.. its like this (studentxmltodatabase.Students@3b9a45b3) can you please help me with this?
    thank you in advance

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.