HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / JAXB / JAXB Write Java Object to XML Example

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?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Sattu

    July 30, 2020

    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

  2. Óscar García

    May 18, 2020

    thanks, easy to find and implement. A reference for when it’s needed.

  3. r k

    April 23, 2020

    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

  4. Omar

    February 2, 2020

    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

    • Asif

      February 26, 2020

      You have to include toString() method in your Student class

  5. sriganth

    January 3, 2019

    how to convert text to java object then java object to xml.

Comments are closed on this article!

Search Tutorials

JAXB Tutorial

  • JAXB – Annotations
  • JAXB – @XmlRootElement
  • JAXB – @XmlElementWrapper
  • JAXB – Marshaller
  • JAXB – Unmarshaller
  • JAXB – Convert XML to Java Object
  • JAXB – Convert JSON to Java Object
  • JAXB – Convert Java Object to XML
  • JAXB – Convert Java Object to JSON
  • JAXB – Map
  • JAXB – List and Set
  • JAXB – Generate Schema
  • JAXB – Schema Validation
  • JAXB – JAXBException
  • JAXB – IllegalAnnotationExceptions
  • JAXB – Marshal without @XmlRootElement
  • JAXB – Unmarshal without @XmlRootElement
  • Jackson 2 – Object from/to JSON
  • Jackson – Object from/to json
  • Jackson – JSON from/to Map

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces