Introduction

Parsing XML efficiently is essential for Java developers working with configuration files, web services, or data serialization. Java Architecture for XML Binding (JAXB) provides a streamlined way to map XML to Java objects and vice versa. This tutorial offers a step-by-step approach to using JAXB for XML parsing in Java applications.

What is JAXB?

JAXB (Java Architecture for XML Binding) is a Java API that facilitates the conversion between Java objects and XML. It enables developers to parse XML files without needing to manually write parsing logic using DOM or SAX.

Initially included in Java SE 6, JAXB was removed from Java SE 11 onward. However, it remains available as a separate dependency.

Key Features of JAXB

  • Automatic XML to Java Object Mapping – Eliminates the need for manual parsing.
  • Annotation-Based Configuration – Uses Java annotations instead of XML configuration.
  • Schema Generation – Generates XML schemas from Java classes.
  • Customizable Mapping – Allows control over XML representation.
  • Integration with Web Services – Works well with RESTful and SOAP web services.

JAXB Workflow: Parsing XML in Java

JAXB involves two primary operations:

  1. Marshalling: Converting Java objects into XML.
  2. Unmarshalling: Converting XML data into Java objects.

Adding JAXB to Your Project

Since JAXB is no longer included in Java 11+, you must manually add dependencies.

Maven Dependency:

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.1</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jaxb</groupId>
    <artifactId>jaxb-runtime</artifactId>
    <version>2.3.1</version>
</dependency>

Gradle Dependency:

dependencies {
    implementation 'javax.xml.bind:jaxb-api:2.3.1'
    implementation 'org.glassfish.jaxb:jaxb-runtime:2.3.1'
}

JAXB Annotations for XML Parsing

JAXB relies on annotations to map Java classes to XML elements.

  • @XmlRootElement – Specifies the root element of XML.
  • @XmlElement – Maps a Java field to an XML element.
  • @XmlAttribute – Maps a Java field to an XML attribute.
  • @XmlTransient – Excludes a field from XML serialization.
  • @XmlAccessorType – Defines field access levels.

JAXB Example: Parsing XML Data

Step 1: Define the Java Class

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

@XmlRootElement
public class Employee {
    private String name;
    private int id;

    public Employee() {}

    public Employee(String name, int id) {
        this.name = name;
        this.id = id;
    }

    @XmlElement
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @XmlElement
    public int getId() {
        return id;
    }

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

Step 2: Convert Java Object to XML

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.StringWriter;

public class JAXBExample {
    public static void main(String[] args) {
        try {
            Employee employee = new Employee("Alice", 102);
            JAXBContext context = JAXBContext.newInstance(Employee.class);
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            
            StringWriter writer = new StringWriter();
            marshaller.marshal(employee, writer);
            System.out.println(writer.toString());
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }
}

Output:

<Employee>
    <name>Alice</name>
    <id>102</id>
</Employee>

Step 3: Parse XML Data to Java Object

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;

public class JAXBUnmarshalExample {
    public static void main(String[] args) {
        try {
            String xmlData = "<Employee><name>Alice</name><id>102</id></Employee>";
            JAXBContext context = JAXBContext.newInstance(Employee.class);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            
            Employee employee = (Employee) unmarshaller.unmarshal(new StringReader(xmlData));
            System.out.println("Name: " + employee.getName() + ", ID: " + employee.getId());
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }
}

Output:

Name: Alice, ID: 102

External Resources

FAQs

1. What is JAXB used for?

JAXB is used to convert Java objects into XML and vice versa, simplifying XML processing.

2. Is JAXB included in Java 11?

No, JAXB was removed in Java 11, but you can manually add the dependencies.

3. How does JAXB differ from DOM and SAX?

JAXB provides automatic object mapping, whereas DOM and SAX require manual parsing.

4. Can JAXB work with JSON?

Yes, JAXB can be extended to support JSON with libraries like Jackson.

5. How do I ignore a field in JAXB?

Use @XmlTransient to exclude a field from XML serialization.

6. Can JAXB generate Java classes from XML schema?

Yes, JAXB can generate Java classes using the xjc tool.

7. Is JAXB thread-safe?

JAXBContext is thread-safe, but Marshaller and Unmarshaller are not.

8. Can JAXB handle complex XML structures?

Yes, JAXB supports nested objects and complex XML structures.

9. What is an alternative to JAXB?

Alternatives include Jackson (for JSON) and StAX (Streaming API for XML).

10. Can JAXB be used for RESTful web services?

Yes, JAXB integrates seamlessly with JAX-RS for XML data exchange.