XML Marshalling – Convert Java Objects to XML using JAXB Version 3

When working with XML in Java applications, Java Architecture for XML Binding (JAXB) simplifies the process by providing a convenient way to map Java objects to XML documents. This blog will focus on XML Marshalling, where we convert Java objects into XML format, using JAXB Version 3.


What is JAXB?

JAXB is a part of the Java EE (now Jakarta EE) specification that allows Java developers to map Java objects to XML and vice versa. It uses annotations to define the mapping between fields in Java classes and the corresponding XML elements.

With JAXB 3.x (part of Jakarta XML Binding), JAXB has been updated to align with the Jakarta namespace.


Dependencies

To use JAXB 3.x in your project, include the required dependency in your Maven pom.xml:

<dependency>

    <groupId>jakarta.xml.bind</groupId>

    <artifactId>jakarta.xml.bind-api</artifactId>

    <version>3.0.1</version>

</dependency>

<dependency>

    <groupId>org.glassfish.jaxb</groupId>

    <artifactId>jaxb-runtime</artifactId>

    <version>3.0.1</version>

</dependency>

Example: Marshalling Java Objects to XML

Let’s go through an example where we marshal a simple Java object to XML.

Step 1: Define the Java Class

Create a Java class representing the data structure. Use JAXB annotations to define the mapping.

Step 2: Marshalling Logic

Write code to convert the Book object into an XML string.

import jakarta.xml.bind.JAXBContext;

import jakarta.xml.bind.JAXBException;

import jakarta.xml.bind.Marshaller;


import java.io.StringWriter;


public class MarshallingExample {

    public static void main(String[] args) {

        try {

            // Create a Book object

            Book book = new Book("Effective Java", "Joshua Bloch", 45.99);


            // Create JAXBContext for the Book class

            JAXBContext context = JAXBContext.newInstance(Book.class);


            // Create Marshaller instance

            Marshaller marshaller = context.createMarshaller();


            // Optional: Format the XML output

            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);


            // Convert object to XML

            StringWriter writer = new StringWriter();

            marshaller.marshal(book, writer);


            // Print the XML string

            System.out.println(writer.toString());

        } catch (JAXBException e) {

            e.printStackTrace();

        }

    }

}

Output

Running the above code will produce the following formatted XML:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

<book>

    <title>Effective Java</title>

    <author>Joshua Bloch</author>

    <price>45.99</price>

</book>

Key JAXB Annotations

  • @XmlRootElement: Marks the class as the root element of the XML.
  • @XmlElement: Maps a field or getter method to an XML element.
  • @XmlAttribute: Maps a field or getter method to an XML attribute (not used in this example).

Tips and Best Practices

  1. Namespace Support: Add namespaces to your XML by using @XmlSchema at the package level.
  2. Validation: Use schema validation to ensure the generated XML meets specific requirements.
  3. Advanced Mapping: Explore @XmlElementWrapper for collections and @XmlTransient to ignore fields.

Followers