Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

This is an introductory tutorial on JAXB (Java Architecture for XML Binding).

First, we’ll show how to convert Java objects to XML and vice versa.

Then we’ll focus on generating Java classes from XML schema and vice versa by using the JAXB-2 Maven plugin.

Further reading:

Unmarshalling Dates Using JAXB

JAXB has basic support for reading data formats built in. Let's extend this functionality to support unconventional formats and the Java 8 Date/Time types.

XML Libraries Support in Java

A quick and practical guide to XML Java tools

Modifying an XML Attribute in Java

Learn how to modify attributes in an XML document using Java with JAXP, dom4j, and jOOX

2. Introduction to JAXB

JAXB provides a fast and convenient way to marshal (write) Java objects into XML and unmarshal (read) XML into objects. It supports a binding framework that maps XML elements and attributes to Java fields and properties using Java annotations.

The JAXB-2 Maven plugin delegates most of its work to either of the two JDK-supplied tools XJC and Schemagen.

3. JAXB Annotations

JAXB uses Java annotations to augment the generated classes with additional information. Adding such annotations to existing Java classes prepares them for the JAXB runtime.

Let’s first create a simple Java object to illustrate marshalling and unmarshalling:

@XmlRootElement(name = "book")
@XmlType(propOrder = { "id", "name", "date" })
public class Book {
    private Long id;
    private String name;
    private String author;
    private Date date;

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

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

    @XmlTransient
    public void setAuthor(String author) {
        this.author = author;
    }
    
    // constructor, getters and setters
}

The class above contains these annotations:

  • @XmlRootElement: The name of the root XML element is derived from the class name, and we can also specify the name of the root element of the XML using its name attribute.
  • @XmlType: define the order in which the fields are written in the XML file
  • @XmlElement: define the actual XML element name that will be used
  • @XmlAttribute: define the id field is mapped as an attribute instead of an element
  • @XmlTransient: annotate fields that we don’t want to be included in XML

For more details on JAXB annotation, check out this link.

4. Marshalling – Converting Java Object to XML

Marshalling gives a client application the ability to convert a JAXB-derived Java object tree into XML data. By default, the Marshaller uses UTF-8 encoding when generating XML data. Next, we will generate XML files from Java objects.

Let’s create a simple program using the JAXBContext, which provides an abstraction for managing the XML/Java binding information necessary to implement the JAXB binding framework operations:

public void marshal() throws JAXBException, IOException {
    Book book = new Book();
    book.setId(1L);
    book.setName("Book1");
    book.setAuthor("Author1");
    book.setDate(new Date());

    JAXBContext context = JAXBContext.newInstance(Book.class);
    Marshaller mar= context.createMarshaller();
    mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    mar.marshal(book, new File("./book.xml"));
}

The jakarta.xml.bind.JAXBContext class provides a client’s entry point to JAXB API. By default, JAXB does not format the XML document. This saves space and prevents that any whitespace is accidentally interpreted as significant.

To have JAXB format the output, we simply set the Marshaller.JAXB_FORMATTED_OUTPUT property to true on the Marshaller. The marshal method uses an object and an output file to store the generated XML as parameters.

When we run the code above, we can check the result in the book.xml to verify that we have successfully converted a Java object into XML data:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<book id="1">
    <title>Book1</title>
    <date>2016-11-12T11:25:12.227+07:00</date>
</book>

5. Unmarshalling – Converting XML to Java Object

Unmarshalling gives a client application the ability to convert XML data into JAXB-derived Java objects.

Let’s use JAXB Unmarshaller to unmarshal our book.xml back to a Java object:

public Book unmarshal() throws JAXBException, IOException {
    JAXBContext context = JAXBContext.newInstance(Book.class);
    return (Book) context.createUnmarshaller()
      .unmarshal(new FileReader("./book.xml"));
}

When we run the code above, we can check the console output to verify that we have successfully converted XML data into a Java object:

Book [id=1, name=Book1, author=null, date=Sat Nov 12 11:38:18 ICT 2016]

6. Complex Data Types

When handling complex data types that may not be directly available in JAXB, we can write an adapter to indicate to JAXB how to manage a specific type.

To do this, we’ll use JAXB’s XmlAdapter to define a custom code to convert an unmappable class into something that JAXB can handle. The @XmlJavaTypeAdapter annotation uses an adapter that extends the XmlAdapter class for custom marshalling.

Let’s create an adapter to specify a date format when marshalling:

public class DateAdapter extends XmlAdapter<String, Date> {

    private static final ThreadLocal<DateFormat> dateFormat 
      = new ThreadLocal<DateFormat>() {

        @Override
        protected DateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    };

    @Override
    public Date unmarshal(String v) throws Exception {
        return dateFormat.get().parse(v);
    }

    @Override
    public String marshal(Date v) throws Exception {
        return dateFormat.get().format(v);
    }
}

We use a date format yyyy-MM-dd HH:mm:ss to convert Date to String when marshalling and ThreadLocal to make our DateFormat thread-safe.

Let’s apply the DateAdapter to our Book:

@XmlRootElement(name = "book")
@XmlType(propOrder = { "id", "name", "date" })
public class Book {
    private Long id;
    private String name;
    private String author;
    private Date date;

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

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

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

    @XmlJavaTypeAdapter(DateAdapter.class)
    public void setDate(Date date) {
        this.date = date;
    }
}

When we run the code above, we can check the result in the book.xml to verify that we have successfully converted our Java object into XML using the new date format yyyy-MM-dd HH:mm:ss:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<book id="1">
    <title>Book1</title>
    <date>2016-11-10 23:44:18</date>final
</book>

7. JAXB-2 Maven Plugin

This plugin uses the Java API for XML Binding (JAXB), version 2+, to generate Java classes from XML Schemas (and optionally binding files) or to create XML schema from an annotated Java class.

Note that there are two fundamental approaches to building web services, Contract Last and Contract First. For more details on these approaches, check out this link.

7.1. Generating a Java Class From XSD

The JAXB-2 Maven plugin uses the JDK-supplied tool XJC, a JAXB Binding compiler tool that generates Java classes from XSD (XML Schema Definition).

Let’s create a simple user.xsd file and use the JAXB-2 Maven plugin to generate Java classes from this XSD schema:

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
    targetNamespace="/jaxb/gen"
    xmlns:userns="/jaxb/gen"
    elementFormDefault="qualified">

    <element name="userRequest" type="userns:UserRequest"></element>
    <element name="userResponse" type="userns:UserResponse"></element>

    <complexType name="UserRequest">
        <sequence>
            <element name="id" type="int" />
            <element name="name" type="string" />
        </sequence>
    </complexType>

    <complexType name="UserResponse">
        <sequence>
            <element name="id" type="int" />
            <element name="name" type="string" />
            <element name="gender" type="string" />
            <element name="created" type="dateTime" />
        </sequence>
    </complexType>
</schema>

Let’s configure the JAXB-2 Maven plugin:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>jaxb2-maven-plugin</artifactId>
    <version>3.1.0</version>
    <executions>
        <execution>
            <id>xjc</id>
            <goals>
                <goal>xjc</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <xjbSources>
            <xjbSource>src/main/resources/global.xjb</xjbSource>
        </xjbSources>
        <sources>
            <source>src/main/resources/user.xsd</source>
        </sources>
        <outputDirectory>${basedir}/src/main/java</outputDirectory>
        <clearOutputDir>false</clearOutputDir>
    </configuration>
</plugin>

By default, this plugin locates XSD files in src/main/xsd. We can configure XSD lookup by modifying the configuration section of this plugin in the pom.xml accordingly.

Also by default, these Java Classes are generated in the target/generated-resources/jaxb folder. We can change the output directory by adding an outputDirectory element to the plugin configuration. We can also add a clearOutputDir element with a value of false to prevent the files in this directory from being erased.

Additionally, we can configure a global JAXB binding that overrides the default binding rules:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<jaxb:bindings version="3.0" xmlns:jaxb="https://jakarta.ee/xml/ns/jaxb"
    xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc" xmlns:xs="http://www.w3.org/2001/XMLSchema"
    jaxb:extensionBindingPrefixes="xjc">

    <jaxb:globalBindings>
        <xjc:simple />
        <xjc:serializable uid="-1" />
        <jaxb:javaType name="java.util.Calendar" xmlType="xs:dateTime"
            parseMethod="jakarta.xml.bind.DatatypeConverter.parseDateTime"
            printMethod="jakarta.xml.bind.DatatypeConverter.printDateTime" />
    </jaxb:globalBindings>
</jaxb:bindings>

The global.xjb above overrides the dateTime type to the java.util.Calendar type.

When we build the project, it generates class files in the src/main/java folder and package com.baeldung.jaxb.gen.

7.2. Generating XSD Schema From Java

The same plugin uses the JDK-supplied tool Schemagen. This is a JAXB Binding compiler tool that can generate an XSD schema from Java classes. In order for a Java Class to be eligible for an XSD schema candidate, the class must be annotated with a @XmlType annotation.

We’ll reuse the Java class files from the previous example to configure the plugin:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>jaxb2-maven-plugin</artifactId>
    <version>3.1.0</version>
    <executions>
        <execution>
            <id>schemagen</id>
            <goals>
                <goal>schemagen</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <sources>
            <source>src/main/java/com/baeldung/jaxb/gen</source>
        </sources>
        <outputDirectory>src/main/resources</outputDirectory>
        <clearOutputDir>false</clearOutputDir>
        <transformSchemas>
            <transformSchema>
                <uri>/jaxb/gen</uri>
                <toPrefix>user</toPrefix>
                <toFile>user-gen.xsd</toFile>
            </transformSchema>
        </transformSchemas>
    </configuration>
</plugin>

By default, JAXB recursively scans all the folders under src/main/java for annotated JAXB classes. We can specify a different source folder for our JAXB-annotated classes by adding a source element to the plugin configuration.

We can also register a transformSchemas, a post processor responsible for naming the XSD schema. It works by matching the namespace with the namespace of the @XmlType of our Java Class.

When we build the project, it generates a user-gen.xsd file in the src/main/resources directory.

8. Conclusion

In this article, we covered introductory concepts on JAXB. For more details, take a look at the JAXB home page.

We can find the source code for this article over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.