JAXB - How to Convert Java Object to / from XML

In this tutorial, we will show you how to use the JAXB API to convert Java Object to/from XML. In this tutorial examples, we use JDK 11 and maven to create our applications.
Learn complete Java XML tutorial at https://www.javaguides.net/p/java-xml-tutorial.html.

JAXB

Java Architecture for XML Binding (JAXB) is a Java standard that allows Java developers to map Java classes to XML representations. JAXB enables to marshal Java objects into XML and unmarshal XML back into Java objects.

Marshalling is the process of transforming Java objects into XML documents. 
Unmarshalling is the process of reading XML documents into Java objects. 

In Java 9, JAXB has moved into a separate module java.xml. In Java 9 and Java 10 we need to use the --add-modules=java.xml.bind option. In Java 11, JAXB has been removed from JDK and we need to add it to the project as a separate library via Maven or Gradle.

Video Tutorial


This tutorial explained in below YouTube video:
In our examples, we use JDK 11 and Maven to create our applications.

Development Steps

1. Create a simple Maven project
2. Add maven dependencies
3. Create POJO classes and Add JAXB annotations
4. Convert Java Object to an XML
5. Convert XML to Java Object

1. Create a Simple Maven Project

Create a simple maven project using the following guide:

2. Add Maven Dependencies

The following POM file includes the necessary JAXB JARs.
<project
    xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>net.javaguides.xml</groupId>
    <artifactId>java-xml-tutorial</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.2.11</version>
        </dependency>
        <dependency>
            <groupId>com.sun.xml.bind</groupId>
            <artifactId>jaxb-core</artifactId>
            <version>2.2.11</version>
        </dependency>
        <dependency>
            <groupId>com.sun.xml.bind</groupId>
            <artifactId>jaxb-impl</artifactId>
            <version>2.2.11</version>
        </dependency>
        <dependency>
            <groupId>javax.activation</groupId>
            <artifactId>activation</artifactId>
            <version>1.1.1</version>
        </dependency>
    </dependencies>
    <build>
        <sourceDirectory>src/main/java</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

3. 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”

3.1 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;
    }
}

3.2 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;
    }
}

4. 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>

5. Convert XML to Java Object

Let's convert the XML document that was generated in the above example to Java object. 

Let's convert a bookstore-jaxb.xml document into Java Object:
package net.javaguides.javaxmlparser.jaxb;

import java.io.File;
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.Unmarshaller;

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

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

        convertXMLToObject();
    }

    private static Bookstore convertXMLToObject() {
        try {
            JAXBContext context = JAXBContext.newInstance(Bookstore.class);
            Unmarshaller un = context.createUnmarshaller();
            Bookstore bookstore = (Bookstore) un.unmarshal(new File(BOOKSTORE_XML));
            List < Book > list = bookstore.getBooksList();
            for (Book book: list) {
                System.out.println("Book: " + book.getName() + " from " + book.getAuthor());
            }
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return null;
    }
}
Output:
Book: Effective Java from Joshua Bloch
Book: Head First Java, 2nd Edition from Kathy Sierra

Conclusion

In this tutorial, we have seen how to use JAXB API to convert Java object to/from XML. In this tutorial, we have used Java 11 to develop and run the examples.
Learn complete Java XML tutorial at https://www.javaguides.net/p/java-xml-tutorial.html.

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments