This tutorial explains how to use JABX(Java Architecture for XML Binding) to parse XML documents to Java objects and vice versa.

1. Overview

Java Architecture for XML Binding (JAXB) is a standard that defines an API for reading and writing Java objects to and from XML documents. It applies a lot of defaults, thus making reading and writing of XML via Java relatively easy.

JAXB uses annotations in Java classes to add the necessary metadata for XML conversion. The following table gives an overview of the important annotations, their usage is demonstrated in the following examples.

Table 1. JAXB annotations
Annotation Description

@XmlRootElement(namespace = "namespace")

Define the root element for an XML tree

@XmlType(propOrder = { "field2", "field1",.. })

Allows to define the order in which the fields are written in the XML file

@XmlElement(name = "neuName")

Define the XML element which will be used. Only need to be used if the neuNeu is different than the JavaBeans Name

JAXB defines a service provider which supports that you exchange the used JAXB implementation.

As of Java 11, JAXB is not part of the JRE anymore and you need to configure the relevant libraries via your dependency management system, for example Maven or Gradle.

For example to convert a String into a annotate`Task` class, you could use the following code:

JAXBContext jaxbContext = JAXBContext.newInstance(Task.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

StringReader reader = new StringReader("xml string here");
Task task = (Task) unmarshaller.unmarshal(reader);

2. Prerequisitions

The following will demonstrate the JAXB API. For an introduction into using XML with Java please see Java XML tutorial.

3. Tutorial: Using JAXB with Gradle

Create a new Gradle project called com.vogella.xml.jaxb.gradle.

Adjust your build.gradle file to include the javax.xml.bind and org.eclipse.persistence libraries as dependencies to your Gradle plug-in.

plugins {
    // Apply the java-library plugin to add support for Java Library
    id 'java-library'
}

repositories {
    // Use jcenter for resolving dependencies.
    // You can declare any Maven/Ivy/file repository here.
    jcenter()
}

dependencies {
    implementation 'javax.xml.bind:jaxb-api:2.3.1'
    implementation'org.eclipse.persistence:org.eclipse.persistence.moxy:2.7.3'

    // Use JUnit test framework
    testImplementation 'junit:junit:4.12'
}

Create the following domain model.

package com.vogella.xml.jaxb.gradle.model;

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

@XmlRootElement(name = "book")
// If you want you can define the order in which the fields are written
// Optional
@XmlType(propOrder = { "author", "name", "publisher", "isbn" })
public class Book {

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

    // If you like the variable name, e.g. "name", you can easily change this
    // name for your XML-Output:
    @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;
    }
}
package com.vogella.xml.jaxb.gradle.model;

import java.util.List;

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

//This statement means that class "Bookstore.java" is the root-element of our example
@XmlRootElement(namespace = "com.vogella.xml.jaxb.gradle.model")
public class Bookstore {

    // XmLElementWrapper generates a wrapper element around XML representation
    @XmlElementWrapper(name = "bookList")
    // XmlElement sets the name of the entities
    @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;
    }
}

As we are using org.eclipse.persistence.moxy for the persistence we also need to create a jaxb.properties file in the package of the model classes.

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

Create the following test program for writing and reading the XML file.

package com.vogella.xml.jaxb.gradle;

import java.io.File;
import java.io.FileReader;
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;
import javax.xml.bind.Unmarshaller;

import com.vogella.xml.jaxb.gradle.model.Book;
import com.vogella.xml.jaxb.gradle.model.Bookstore;

public class BookMain {

    private static final String BOOKSTORE_XML = "./bookstore-jaxb.xml";

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

        var bookList = new ArrayList<Book>();

        // create books
        var book1 = new Book();
        book1.setIsbn("978-0060554736");
        book1.setName("The Game");
        book1.setAuthor("Neil Strauss");
        book1.setPublisher("Harpercollins");
        bookList.add(book1);

        var book2 = new Book();
        book2.setIsbn("978-3832180577");
        book2.setName("Feuchtgebiete");
        book2.setAuthor("Charlotte Roche");
        book2.setPublisher("Dumont Buchverlag");
        bookList.add(book2);

        // create bookstore, assigning book
        var bookstore = new Bookstore();
        bookstore.setName("Fraport Bookstore");
        bookstore.setLocation("Frankfurt Airport");
        bookstore.setBookList(bookList);

        // 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));

        // get variables from our xml file, created before
        System.out.println();
        System.out.println("Output from our XML File: ");
        Unmarshaller um = context.createUnmarshaller();
        Bookstore bookstore2 = (Bookstore) um.unmarshal(new FileReader(
                BOOKSTORE_XML));
        List<Book> list = bookstore2.getBooksList();
        for (Book book : list) {
            System.out.println("Book: " + book.getName() + " from "
                    + book.getAuthor());
        }
    }
}

If you run the BookMain an XML file will be created from the input objects. Afterwards the file is read again and the objects are re-created based on the XML file.

4. vogella training and consulting support

Copyright © 2012-2019 vogella GmbH. Free use of the software examples is granted under the terms of the Eclipse Public License 2.0. This tutorial is published under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Germany license.