Java Architecture for XML Binding (JAXB) is a popular choice for mapping Java objects to and from XML. It provides an easy to use programming interface for reading and writing Java objects to XML and vice versa.

In this quick guide, you'll learn how to transform a Java object to an XML document. We'll also look at an example to convert an XML document back to a Java object.

Dependencies

JAXB is a part of the Java Development Kit (JDK) since Java 1.6. So you don't need any 3rd-party dependency to use JAXB in your project.

Marshalling — Java Object to XML

In JAXB terminology, Java object to XML conversion is referred to as marshalling. Marshalling a process of converting a Java object to an XML document. JAXB provides the Marshall class to perform this conversion.

Create Java Classes

Before we actually discuss how marshaling works, let us first create two simple Java classes called Author and Book. These classes model a very simple scenario where we have books and each book has exactly one author.

We start by creating the Author class to model the author:

Author.java

public class Author {

    private Long id;
    private String firstName;
    private String lastName;

    public Author() {
    }

    public Author(Long id, String firstName, String lastName) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return "Author{" +
                "id=" + id +
                ", firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                '}';
    }
}

Author is a simple Java class with an ID, first and last names, along with their corresponding getting and setter methods.

Next, we will create the Book class and annotate its fields with JAXB annotations to control how it should be marshalled to XML:

Book.java

@XmlRootElement(name = "book")
public class Book {

    private Long id;
    private String title;
    private String isbn;
    private Author author;

    public Book() {
    }

    public Book(Long id, String title, String isbn, Author author) {
        this.id = id;
        this.title = title;
        this.isbn = isbn;
        this.author = author;
    }

    public Long getId() {
        return id;
    }

    @XmlAttribute(name = "id")
    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    @XmlElement(name = "title")
    public void setTitle(String title) {
        this.title = title;
    }

    public String getIsbn() {
        return isbn;
    }

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

    public Author getAuthor() {
        return author;
    }

    @XmlElement(name = "author")
    public void setAuthor(Author author) {
        this.author = author;
    }

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", isbn='" + isbn + '\'' +
                ", author=" + author +
                '}';
    }
}

In the Book class above, we used several JAXB annotations:

  • @XmlRootElement — This annotation is used at the top-level class to specify the root element of the XML document. The name attribute in the annotation is optional. If not specified, the class name is used as the name of the root element in the XML document.
  • @XmlAttribute — This annotation is used to indicate the attribute of the root element.
  • @XmlElement — This annotation is used on the fields of the class that will be the sub-elements of the root element.

That's it. The Book class is now ready to be marshaled into an XML document. Let us start with a simple scenario where you want to convert a Java Object to an XML string.

Convert Java Object to XML String

To convert a Java object to an XML string, you need to first create an instance of JAXBContext. This is the entry point to JAXB API that provides several methods to marshal, unmarshal, and validate XML documents.

Next, get the Marshall instance from JAXBContext. Afterward, use its marshal() method to marshall a Java object to XML. You can write the generated XML to a file, string, or just print it on the console.

Here is an example that converts a Book object to an XML string:

try {
    // create an instance of `JAXBContext`
    JAXBContext context = JAXBContext.newInstance(Book.class);

    // create an instance of `Marshaller`
    Marshaller marshaller = context.createMarshaller();

    // enable pretty-print XML output
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    // write XML to `StringWriter`
    StringWriter sw = new StringWriter();

    // create `Book` object
    Book book = new Book(17L, "Head First Java", "ISBN-45565-45",
            new Author(5L, "Bert", "Bates"));

    // convert book object to XML
    marshaller.marshal(book, sw);

    // print the XML
    System.out.println(sw.toString());

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

The above code will print the following on the console:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<book id="17">
    <author>
        <firstName>Bert</firstName>
        <id>5</id>
        <lastName>Bates</lastName>
    </author>
    <isbn>ISBN-45565-45</isbn>
    <title>Head First Java</title>
</book>

Convert Java Object to XML File

Java object to an XML file conversion is very much similar to the above example. All you need to do is just replace the StringWriter instance with an instance of File where you want to store the XML:

try {
    // create an instance of `JAXBContext`
    JAXBContext context = JAXBContext.newInstance(Book.class);

    // create an instance of `Marshaller`
    Marshaller marshaller = context.createMarshaller();

    // enable pretty-print XML output
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    // create XML file
    File file = new File("book.xml");

    // create `Book` object
    Book book = new Book(17L, "Head First Java", "ISBN-45565-45",
            new Author(5L, "Bert", "Bates"));

    // convert book object to XML file
    marshaller.marshal(book, file);

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

Now if you execute the above code snippet, you should see an XML file called book.xml generated with the same XML content as we have seen in the above example.

Unmarshalling — XML to Java Object

XML to Java object conversion or unmarshalling involves creating an instance of Unmarshaller from the JAXBContext and calling the unmarshal() method. This method accepts the XML file as an argument to unmarshal.

The following example shows how you can convert the book.xml file, we just created above, into an instance of Book:

try {
    // create an instance of `JAXBContext`
    JAXBContext context = JAXBContext.newInstance(Book.class);

    // create an instance of `Unmarshaller`
    Unmarshaller unmarshaller = context.createUnmarshaller();

    // XML file path
    File file = new File("book.xml");

    // convert XML file to `Book` object
    Book book = (Book) unmarshaller.unmarshal(file);

    // print book object
    System.out.println(book);

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

Here is the output of the above example:

Book{id=17, title='Head First Java', isbn='ISBN-45565-45', author=Author{id=5, firstName='Bert', lastName='Bates'}}

Marshall Java Collections to XML

Many times you want to marshal Java collection objects such as List, Map, or Set to an XML document, and also convert XML back to Java collection objects.

For such a scenario, we need to create a special class named Books that holds a List of Book objects. Here is how it looks like:

Books.java

@XmlRootElement(name = "books")
public class Books {

    private List<Book> books;

    public List<Book> getBooks() {
        return books;
    }

    @XmlElement(name = "book")
    public void setBooks(List<Book> books) {
        this.books = books;
    }

    public void add(Book book) {
        if (this.books == null) {
            this.books = new ArrayList<>();
        }
        this.books.add(book);
    }
}

In the Books class above, the @XmlRootElement annotation indicates the root element of the XML as books. This class has a single List field with getter and setter methods. The add() method of this class accepts a Book object and adds it to the list.

The following example demonstrates how you can convert a Java collection object into an XML document:

try {
    // create an instance of `JAXBContext`
    JAXBContext context = JAXBContext.newInstance(Books.class);

    // create an instance of `Marshaller`
    Marshaller marshaller = context.createMarshaller();

    // enable pretty-print XML output
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    // create `Books` object
    Books books = new Books();

    // add books to list
    books.add(new Book(1L, "Head First Java", "ISBN-45565-45",
            new Author(1L, "Bert", "Bates")));
    books.add(new Book(2L, "Thinking in Java", "ISBN-95855-3",
            new Author(2L, "Bruce", "Eckel")));

    // convert `Books` object to XML file
    marshaller.marshal(books, new File("books.xml"));

    // print XML to console
    marshaller.marshal(books, System.out);

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

The above example will output the following XML into books.xml file as well as on the console:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<books>
    <book id="1">
        <author>
            <firstName>Bert</firstName>
            <id>1</id>
            <lastName>Bates</lastName>
        </author>
        <isbn>ISBN-45565-45</isbn>
        <title>Head First Java</title>
    </book>
    <book id="2">
        <author>
            <firstName>Bruce</firstName>
            <id>2</id>
            <lastName>Eckel</lastName>
        </author>
        <isbn>ISBN-95855-3</isbn>
        <title>Thinking in Java</title>
    </book>
</books>

Conclusion

That's all folks for converting a Java object to an XML document and vice versa. We learned how to marshal a Java object or a Java collection object into an XML file. Similarly, we also looked at an example to convert an XML document back to a Java object.

If you want to learn more about XML processing in Java and Spring Boot, check out the following two articles:

✌️ Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. Subscribe to RSS Feed.

👋 If you enjoy reading my articles and want to support me to continue creating free tutorials, Buy me a coffee (cost $5) .

Need help to launch a new product? I am available for contract work. Hire me to accomplish your business goals with engineering and design.