How to Convert Java Object to XML - JAXB Marshalling

In this article, we will learn how to convert Java object to XML using Java Architecture for XML Binding (JAXB).
Java Architecture for XML Binding (JAXB) is a Java standard that defines how Java objects are converted from and to XML. It uses a standard set of mappings.
JAXB API provides a Marshaller interface, we can marshal(write) method to convert Java object into an XML document.
Let's see the steps to convert Java object into an XML document.
  1. Create POJO or bind the schema and generate the classes
  2. Create the JAXBContext object
  3. Create the Marshaller objects
  4. Create the content tree by using set methods
  5. Call the marshal method

Create POJO classes and Add JAXB annotations

Some basic and useful JAXB annotations are:
  1. @XmlRootElement: This is a must-have an annotation for the Object to be used in JAXB. It defines the root element for the XML content.
  2. @XmlType: It maps the class to the XML schema type. We can use it for ordering the elements in the XML.
  3. @XmlTransient: This will make sure that the Object property is not written to the XML.
  4. @XmlAttribute: This will create the Object property as an attribute.
  5. @XmlElement(name = “ABC”): This will create the element with name “ABC”

Book POJO Class

package net.javaguides.javaxmlparser.jaxb;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlRootElement(name = "book")
@XmlType(propOrder = {
    "author",
    "name",
    "publisher",
    "isbn"
})
public class Book {

    private String name;
    private String author;
    private String publisher;
    private String isbn;

    @XmlElement(name = "title")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getPublisher() {
        return publisher;
    }

    public void setPublisher(String publisher) {
        this.publisher = publisher;
    }

    public String getIsbn() {
        return isbn;
    }

    public void setIsbn(String isbn) {
        this.isbn = isbn;
    }
}

Bookstore POJO Class

package net.javaguides.javaxmlparser.jaxb;

import java.util.List;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(namespace = "net.javaguides.javaxmlparser.jaxb")
public class Bookstore {

    @XmlElementWrapper(name = "bookList")
    @XmlElement(name = "book")
    private List < Book > bookList;
    private String name;
    private String location;

    public void setBookList(List < Book > bookList) {
        this.bookList = bookList;
    }

    public List < Book > getBooksList() {
        return bookList;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }
}

Marshaller Class - Convert Java Object to an XML

package net.javaguides.javaxmlparser.jaxb;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

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

/**
 * Marshaller Class - Convert Java Object to XML
 * 
 * @author Ramesh Fadatare
 *
 */
public class BookMain {
    private static final String BOOKSTORE_XML = "bookstore-jaxb.xml";

    public static void main(String[] args) throws JAXBException, IOException {

        List < Book > bookList = new ArrayList < Book > ();

        // create books
        Book book1 = new Book();
        book1.setIsbn("978-0134685991");
        book1.setName("Effective Java");
        book1.setAuthor("Joshua Bloch");
        book1.setPublisher("Amazon");
        bookList.add(book1);

        Book book2 = new Book();
        book2.setIsbn("978-0596009205");
        book2.setName("Head First Java, 2nd Edition");
        book2.setAuthor("Kathy Sierra");
        book2.setPublisher("amazon");
        bookList.add(book2);

        // create bookstore, assigning book
        Bookstore bookstore = new Bookstore();
        bookstore.setName("Amazon Bookstore");
        bookstore.setLocation("Newyorkt");
        bookstore.setBookList(bookList);

        convertObjectToXML(bookstore);

    }

    private static void convertObjectToXML(Bookstore bookstore) throws JAXBException, FileNotFoundException {
        // create JAXB context and instantiate marshaller
        JAXBContext context = JAXBContext.newInstance(Bookstore.class);
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        // Write to System.out
        m.marshal(bookstore, System.out);

        // Write to File
        m.marshal(bookstore, new File(BOOKSTORE_XML));
    }
}
The above program creates a file named bookstore-jaxb.xml and stored Book objects into this XML file:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:bookstore xmlns:ns2="net.javaguides.javaxmlparser.jaxb">
    <bookList>
        <book>
            <author>Joshua Bloch</author>
            <title>Effective Java</title>
            <publisher>Amazon</publisher>
            <isbn>978-0134685991</isbn>
        </book>
        <book>
            <author>Kathy Sierra</author>
            <title>Head First Java, 2nd Edition</title>
            <publisher>amazon</publisher>
            <isbn>978-0596009205</isbn>
        </book>
    </bookList>
    <location>Newyorkt</location>
    <name>Amazon Bookstore</name>
</ns2:bookstore>

Comments