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 !!

Leave a Reply

6 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

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

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

Our Blogs

REST API Tutorial