JAXB in Java: Binding Objects to XML with Jakarta XML Binding

JAXB (now Jakarta XML Binding) maps Java classes to XML with annotations, so a whole document becomes an object graph in one call and back again. This page runs every example against jakarta.xml.bind-api 4.0.2 and the GlassFish runtime 4.0.8, and shows what JAXB checks, what it skips without telling you, and how to make it strict.

Share

Contents

How JAXB works

JAXB (Java Architecture for XML Binding) maps between XML and Java objects. You annotate classes, or generate them from an XML Schema with the xjc tool, and JAXB does the parsing and writing. Converting objects to XML is called marshalling, and XML to objects unmarshalling.

Everything starts with a JAXBContext. Creating one inspects every class in the model with reflection, follows references to other classes, checks the annotations and builds a runtime model of how each field maps to elements and attributes. That makes the context slow to create and safe to share. From the context you create a Marshaller, which walks an object graph and writes XML, or an Unmarshaller, which reads XML as a stream of events and creates objects with their no-argument constructors as matching elements arrive.

JAXB versions
VersionYearWhat changed
JAXB 2.02006Annotation-based mapping; bundled with Java 6 as javax.xml.bind
JAXB 2.32017Last version in the JDK; deprecated in Java 9
Removed from the JDK2018Java 11, JEP 320
Jakarta XML Binding 3.02020Package renamed to jakarta.xml.bind
Jakarta XML Binding 4.02022Requires Java 11; used here with the GlassFish runtime 4.0.8

The default mapping (XmlAccessType.PUBLIC_MEMBER) binds public fields and public getter and setter pairs. Most code switches to XmlAccessType.FIELD, as the examples do, so that private fields are bound and getters are not required. All programs ran on JDK 21.

Setup: JAXB is no longer in the JDK

JAXB shipped with Java 6 to 10 as javax.xml.bind. Java 11 removed it (JEP 320), and the API moved to the Eclipse Foundation as Jakarta XML Binding. Version 3 renamed the package to jakarta.xml.bind; version 4 needs Java 11 or later. You now add two dependencies: the API, and an implementation that does the work at run time.

XML
<dependency>
    <groupId>jakarta.xml.bind</groupId>
    <artifactId>jakarta.xml.bind-api</artifactId>
    <version>4.0.2</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jaxb</groupId>
    <artifactId>jaxb-runtime</artifactId>
    <version>4.0.8</version>
    <scope>runtime</scope>
</dependency>

Without the runtime, JAXBContext.newInstance fails with "Implementation of Jakarta XML Binding-API has not been found". Old code that imports javax.xml.bind must change its imports to jakarta.xml.bind; the class and annotation names are the same.

The model: an order with items

The examples use one small model: an order with an id, a customer, a list of items and an optional note. It was chosen so that each common annotation has a job to do. JAXB creates objects with a no-argument constructor and then sets fields, so these are ordinary classes rather than records.

Java
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlElementWrapper;
import jakarta.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.annotation.XmlTransient;
import jakarta.xml.bind.annotation.XmlType;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

// JAXB-mapped classes: JAXB needs a no-argument constructor, so these are classes, not records
final class Model {
    private Model() {
    }

    @XmlRootElement(name = "order")
    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(propOrder = {"customer", "items", "note"})
    static class Order {
        @XmlAttribute
        String id;

        @XmlElement(required = true)
        String customer;

        @XmlElementWrapper(name = "items")
        @XmlElement(name = "item")
        List<Item> items = new ArrayList<>();

        @XmlElement
        String note;                        // null fields are left out of the XML

        @XmlTransient
        String internalStatus = "NEW";      // never written or read

        Order() {
        }

        Order(String id, String customer) {
            this.id = id;
            this.customer = customer;
        }
    }

    @XmlAccessorType(XmlAccessType.FIELD)
    static class Item {
        @XmlAttribute
        String sku;

        @XmlAttribute
        int qty;

        @XmlElement
        BigDecimal price;

        Item() {
        }

        Item(String sku, int qty, String price) {
            this.sku = sku;
            this.qty = qty;
            this.price = new BigDecimal(price);
        }
    }
}
Annotations used in the model
AnnotationEffect here
@XmlRootElement(name = "order")The class can be a whole document, with root tag <order>
@XmlAccessorType(XmlAccessType.FIELD)Bind fields directly; no getters or setters needed
@XmlType(propOrder = ...)Fixes the order of child elements in the output
@XmlAttributeWritten as id="o-7" instead of a child element
@XmlElementWrapper(name = "items") with @XmlElement(name = "item")The list becomes <items><item/><item/></items>; without the wrapper the items would sit directly under <order>
@XmlElement(required = true)Marks the element as required in a generated schema; on its own it does not reject input (shown below)
@XmlTransientExcluded from XML in both directions

Marshal and unmarshal

The program writes an order with two items, reads the XML back, then reads a deliberately incomplete document. The customer name "Ana & Co" contains an ampersand to show that escaping is automatic, and the second price is "24.00" to show that BigDecimal keeps its scale.

Java
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.Marshaller;
import jakarta.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.io.StringWriter;

public class MarshalUnmarshal {

    public static void main(String[] args) throws Exception {
        // JAXBContext is expensive to create and thread-safe: create it once
        JAXBContext ctx = JAXBContext.newInstance(Model.Order.class);

        Model.Order order = new Model.Order("o-7", "Ana & Co");
        order.items.add(new Model.Item("A1", 2, "9.95"));
        order.items.add(new Model.Item("B2", 1, "24.00"));

        // Marshaller and Unmarshaller are cheap but NOT thread-safe: one per use
        Marshaller m = ctx.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        StringWriter xml = new StringWriter();
        m.marshal(order, xml);
        System.out.print(xml);

        Unmarshaller u = ctx.createUnmarshaller();
        Model.Order back = (Model.Order) u.unmarshal(new StringReader(xml.toString()));
        System.out.println("read back: id=" + back.id + ", customer=" + back.customer
                + ", items=" + back.items.size() + ", second price=" + back.items.get(1).price
                + ", internalStatus=" + back.internalStatus);

        // Unknown elements are skipped and "required" is not enforced without a schema
        String sloppy = "<order id=\"o-8\"><extra>?</extra><items><item sku=\"C3\"/></items>"
                + "</order>";
        Model.Order lax = (Model.Order) u.unmarshal(new StringReader(sloppy));
        System.out.println("sloppy input accepted: customer=" + lax.customer + ", qty="
                + lax.items.get(0).qty + ", price=" + lax.items.get(0).price);
    }
}

Output:

Output
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<order id="o-7">
    <customer>Ana &amp; Co</customer>
    <items>
        <item sku="A1" qty="2">
            <price>9.95</price>
        </item>
        <item sku="B2" qty="1">
            <price>24.00</price>
        </item>
    </items>
</order>
read back: id=o-7, customer=Ana & Co, items=2, second price=24.00, internalStatus=NEW
sloppy input accepted: customer=null, qty=0, price=null

What the output shows, in order:

  1. The & was escaped to &amp; and read back as &.
  2. The note field was null, so no <note> element was written. internalStatus is not in the XML at all.
  3. The elements follow propOrder, and the items are inside the <items> wrapper.
  4. After reading back, internalStatus is "NEW" only because the field initializer ran in the no-argument constructor; JAXB never touched it.
  5. The incomplete document has an unknown <extra> element, no customer, and an item with no quantity or price. JAXB accepted it without a word: customer is null even though it is marked required, the missing int is 0, and the missing BigDecimal is null.

JAXBContext is thread-safe and expensive to build, because it inspects every class in the model; create it once and share it. Marshaller and Unmarshaller are cheap and not thread-safe, so create one per operation.

Errors, validation and untrusted input

The last result above is the main trap with JAXB: by default it is lenient. The next program shows the four ways problems surface, plus how it treats an external entity attack. The inputs are small on purpose, each with exactly one defect.

Java
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.UnmarshalException;
import jakarta.xml.bind.Unmarshaller;
import jakarta.xml.bind.ValidationEventHandler;
import jakarta.xml.bind.SchemaOutputResolver;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import javax.xml.XMLConstants;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.Result;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;

public class ValidationAndErrors {

    public static void main(String[] args) throws Exception {
        JAXBContext ctx = JAXBContext.newInstance(Model.Order.class);
        String unknown = "<order id=\"o-9\"><customer>Cho</customer><extra>?</extra></order>";

        // A handler sees problems JAXB would otherwise skip silently
        List<String> problems = new ArrayList<>();
        Unmarshaller u = ctx.createUnmarshaller();
        ValidationEventHandler collect = event -> {
            problems.add(event.getMessage());
            return true;                                 // true = continue parsing
        };
        u.setEventHandler(collect);
        u.unmarshal(new StringReader(unknown));
        System.out.println("problems reported: " + problems.size()
                + (problems.isEmpty() ? "" : " -> " + problems.get(0)));

        // Returning false turns the first problem into an exception
        Unmarshaller strict = ctx.createUnmarshaller();
        strict.setEventHandler(event -> false);
        try {
            strict.unmarshal(new StringReader(unknown));
            System.out.println("strict handler: accepted");
        } catch (UnmarshalException e) {
            System.out.println("strict handler: UnmarshalException");
        }

        // A value that does not fit the Java type fails with a plain runtime exception
        try {
            ctx.createUnmarshaller().unmarshal(new StringReader(
                    "<order id=\"o-9\"><items><item sku=\"C3\" qty=\"many\"/></items></order>"));
        } catch (RuntimeException e) {
            System.out.println("qty=\"many\": " + e.getClass().getSimpleName() + ": "
                    + e.getMessage());
        }

        // A schema makes "required" real: generate one from the classes and attach it
        StringWriter xsd = new StringWriter();
        ctx.generateSchema(new SchemaOutputResolver() {
            @Override
            public Result createOutput(String ns, String file) {
                StreamResult result = new StreamResult(xsd);
                result.setSystemId(file);
                return result;
            }
        });
        Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
                .newSchema(new StreamSource(new StringReader(xsd.toString())));
        Unmarshaller validating = ctx.createUnmarshaller();
        validating.setSchema(schema);
        try {
            validating.unmarshal(new StringReader("<order id=\"o-11\"><items/></order>"));
            System.out.println("schema: accepted");
        } catch (UnmarshalException e) {
            System.out.println("schema: " + e.getLinkedException().getMessage());
        }

        // An external entity that tries to read a local file
        String evil = "<?xml version=\"1.0\"?><!DOCTYPE order [<!ENTITY x SYSTEM "
                + "\"file:///etc/hostname\">]><order id=\"o-10\"><customer>&x;</customer></order>";

        // 1. Default unmarshal: the JAXB runtime blocks external access
        try {
            ctx.createUnmarshaller().unmarshal(new StringReader(evil));
            System.out.println("default: entity resolved");
        } catch (UnmarshalException e) {
            System.out.println("default: " + e.getLinkedException().getMessage());
        }

        // 2. Belt and braces: a StAX reader that refuses DTDs altogether
        XMLInputFactory xif = XMLInputFactory.newInstance();
        xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
        xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
        try {
            XMLStreamReader r = xif.createXMLStreamReader(new StringReader(evil));
            ctx.createUnmarshaller().unmarshal(r);
            System.out.println("no-DTD reader: entity resolved");
        } catch (UnmarshalException e) {
            String msg = e.getLinkedException().getMessage();
            System.out.println("no-DTD reader: " + msg.substring(msg.indexOf("Message: ") + 9));
        }
    }
}

Output:

Output
problems reported: 1 -> unexpected element (uri:"", local:"extra"). Expected elements are <{}note>,<{}items>,<{}customer>
strict handler: UnmarshalException
qty="many": NumberFormatException: Not a number: many
schema: cvc-complex-type.2.4.a: Invalid content was found starting with element 'items'. One of '{customer}' is expected.
default: External Entity: Failed to read external document 'hostname', because 'file' access is not allowed due to restriction set by the accessExternalDTD property.
no-DTD reader: The entity "x" was referenced, but not declared.
How each kind of problem is reported
Input problemDefault behaviorHow to make it fail
Unknown element (<extra>)Skipped; a ValidationEvent is raised but the default handler ignores itAn event handler that returns false (UnmarshalException), or a schema
Missing required elementField stays null; no event at allA schema set with setSchema
Value that does not fit the type (qty="many")An unchecked NumberFormatException escapes from unmarshal, even with an event handler setWith a schema it becomes a validation error instead: "'many' is not a valid value for 'integer'"
External entity reading a fileBlocked by the runtime (accessExternalDTD)Already fails; a reader with DTDs off rejects it earlier

Notes on the output:

  • The event handler's message lists the expected elements, which is useful for logging. Returning true means "continue", so collecting events is a cheap way to audit input without rejecting it.
  • The schema is generated from the classes with generateSchema, so it cannot drift from the model. The error cvc-complex-type.2.4.a says <items> arrived where <customer> was required. In a real project you would usually validate against the published XSD instead.
  • Because NumberFormatException is unchecked, a catch (JAXBException e) block does not catch it. Code that reads input it does not control should either validate with a schema or also catch RuntimeException.
  • For the XXE test, the default unmarshal refused to read /etc/hostname because the GlassFish runtime restricts external access. The StAX reader with SUPPORT_DTD off ignores the DTD entirely, so the entity is simply undeclared. Turning DTDs off does not depend on the runtime's defaults, which is why it is still worth doing for untrusted input. See the DOM parser page for what XXE does when nothing blocks it.

Custom types with XmlAdapter

JAXB maps strings, numbers, BigDecimal, enums and the older java.util.Date and XMLGregorianCalendar types, but it has no mapping for java.time. An XmlAdapter converts between a type JAXB knows (here String) and the one you want. The date 2026-11-14 is used so the day of week can be checked by eye.

Java
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.Marshaller;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.annotation.adapters.XmlAdapter;
import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import java.io.StringReader;
import java.io.StringWriter;
import java.time.LocalDate;

public class TypeAdapter {

    // JAXB has no built-in mapping for java.time types, so an adapter converts them
    public static class LocalDateAdapter extends XmlAdapter<String, LocalDate> {
        @Override
        public LocalDate unmarshal(String text) {
            return LocalDate.parse(text);               // "2026-11-14" -> LocalDate
        }

        @Override
        public String marshal(LocalDate date) {
            return date.toString();                     // LocalDate -> "2026-11-14"
        }
    }

    @XmlRootElement(name = "shipment")
    @XmlAccessorType(XmlAccessType.FIELD)
    static class Shipment {
        @XmlAttribute
        String id;

        @XmlJavaTypeAdapter(LocalDateAdapter.class)
        LocalDate shipped;

        Shipment() {
        }
    }

    public static void main(String[] args) throws Exception {
        JAXBContext ctx = JAXBContext.newInstance(Shipment.class);

        Shipment s = new Shipment();
        s.id = "s-1";
        s.shipped = LocalDate.of(2026, 11, 14);
        Marshaller m = ctx.createMarshaller();
        m.setProperty(Marshaller.JAXB_FRAGMENT, true);  // no <?xml ...?> declaration
        StringWriter xml = new StringWriter();
        m.marshal(s, xml);
        System.out.println(xml);

        Shipment back = (Shipment) ctx.createUnmarshaller()
                .unmarshal(new StringReader(xml.toString()));
        System.out.println("read back: " + back.shipped + " (" + back.shipped.getDayOfWeek()
                + "), class " + back.shipped.getClass().getSimpleName());
    }
}

Output:

Output
<shipment id="s-1"><shipped>2026-11-14</shipped></shipment>
read back: 2026-11-14 (SATURDAY), class LocalDate

JAXB_FRAGMENT leaves out the <?xml ...?> declaration, which helps when the XML is embedded in something else. The value read back is a real LocalDate, not a string. Put the adapter on a package with @XmlJavaTypeAdapters in package-info.java to apply it to every LocalDate field at once.

Inheritance, namespaces and records

A list declared as a base class can hold subclasses, and JAXB has two ways to record which subclass each element is. The payment ledger holds a card payment and a bank transfer, because the two subclasses have different fields. The program also gives one root element a namespace and tries to bind a record.

Java
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.Marshaller;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlElements;
import jakarta.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.annotation.XmlSeeAlso;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

public class Inheritance {

    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlSeeAlso({Card.class, Transfer.class})
    public static class Payment {
        @XmlAttribute
        int cents;
    }

    public static class Card extends Payment {
        String last4;
    }

    public static class Transfer extends Payment {
        String iban;
    }

    // 1. Element name chosen by the subclass
    @XmlRootElement(name = "ledger", namespace = "urn:example:pay")
    @XmlAccessorType(XmlAccessType.FIELD)
    public static class ByElement {
        @XmlElements({@XmlElement(name = "card", type = Card.class),
            @XmlElement(name = "transfer", type = Transfer.class)})
        List<Payment> payments = new ArrayList<>();
    }

    // 2. One element name, the subclass written as xsi:type
    @XmlRootElement(name = "ledger")
    @XmlAccessorType(XmlAccessType.FIELD)
    public static class ByType {
        @XmlElement(name = "payment")
        List<Payment> payments = new ArrayList<>();
    }

    @XmlRootElement
    record Point(int x, int y) {
    }

    static String write(JAXBContext ctx, Object o) throws Exception {
        Marshaller m = ctx.createMarshaller();
        m.setProperty(Marshaller.JAXB_FRAGMENT, true);
        StringWriter out = new StringWriter();
        m.marshal(o, out);
        return out.toString();
    }

    static List<Payment> sample() {
        Card c = new Card();
        c.cents = 1999;
        c.last4 = "4242";
        Transfer t = new Transfer();
        t.cents = 50000;
        t.iban = "NO9386011117947";
        return List.of(c, t);
    }

    public static void main(String[] args) throws Exception {
        JAXBContext byElement = JAXBContext.newInstance(ByElement.class);
        ByElement a = new ByElement();
        a.payments.addAll(sample());
        String xml = write(byElement, a);
        System.out.println("@XmlElements: " + xml);
        ByElement back = (ByElement) byElement.createUnmarshaller()
                .unmarshal(new StringReader(xml));
        System.out.println("  read back as: " + back.payments.stream()
                .map(p -> p.getClass().getSimpleName()).toList());

        JAXBContext byType = JAXBContext.newInstance(ByType.class);
        ByType b = new ByType();
        b.payments.addAll(sample());
        String xml2 = write(byType, b);
        System.out.println("xsi:type:     " + xml2);
        ByType back2 = (ByType) byType.createUnmarshaller().unmarshal(new StringReader(xml2));
        System.out.println("  read back as: " + back2.payments.stream()
                .map(p -> p.getClass().getSimpleName()).toList());

        // Records have no no-argument constructor, so JAXB cannot build them
        try {
            JAXBContext.newInstance(Point.class);
            System.out.println("record: context created");
        } catch (Exception e) {
            System.out.println("record: " + e.getClass().getSimpleName() + ": "
                    + e.getMessage().lines().filter(l -> l.contains("constructor")).findFirst()
                    .orElse(e.getMessage().lines().findFirst().orElse("")).trim());
        }
    }
}

Output:

Output
@XmlElements: <ns2:ledger xmlns:ns2="urn:example:pay"><card cents="1999"><last4>4242</last4></card><transfer cents="50000"><iban>NO9386011117947</iban></transfer></ns2:ledger>
  read back as: [Card, Transfer]
xsi:type:     <ledger><payment xsi:type="card" cents="1999" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><last4>4242</last4></payment><payment xsi:type="transfer" cents="50000" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><iban>NO9386011117947</iban></payment></ledger>
  read back as: [Card, Transfer]
record: IllegalAnnotationsException: - Inheritance$Point does not have a no-arg default constructor.
  • @XmlElements maps each subclass to its own element name, so the ledger contains <card> and <transfer>, and reading back created a Card and a Transfer. This is the more readable format and the usual choice when you design the XML.
  • With a single @XmlElement on a base-class list, JAXB writes every entry as <payment> and adds xsi:type="card" or xsi:type="transfer", using the subclasses listed in @XmlSeeAlso. Without @XmlSeeAlso, the context would not know the subclasses at all.
  • The namespaced root came out as ns2:ledger with xmlns:ns2. The XML is correct, but generated prefixes such as ns2 surprise people. A package-info.java with @XmlSchema(namespace = ..., xmlns = @XmlNs(prefix = "pay", ...)) chooses the prefix, or makes the namespace the default for the package.
  • The record failed with "does not have a no-arg default constructor": JAXB creates objects first and sets fields afterwards, which records do not allow. Use classes for JAXB models, or an XmlAdapter that converts a record to a JAXB-friendly class.

Large documents, and what is expensive

JAXB normally builds the whole object graph, but it can also unmarshal one element at a time from a StAX reader, which keeps memory constant for large feeds. The program streams 50,000 items and totals their value, then compares the cost of creating a JAXBContext with the cost of a marshal call. The timings use a warm-up run and the best of 3 runs, on a 2-CPU Linux machine; they are a rough guide only.

Java
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBElement;
import jakarta.xml.bind.Marshaller;
import jakarta.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.io.StringWriter;
import java.math.BigDecimal;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;

public class StreamingAndCost {

    public static void main(String[] args) throws Exception {
        // A large feed of <item> elements, read one item at a time
        StringBuilder sb = new StringBuilder("<feed>");
        for (int i = 0; i < 50000; i++) {
            sb.append("<item sku=\"s").append(i).append("\" qty=\"").append(i % 5 + 1)
                    .append("\"><price>").append(i % 100).append(".50</price></item>");
        }
        String xml = sb.append("</feed>").toString();

        JAXBContext ctx = JAXBContext.newInstance(Model.Item.class);
        Unmarshaller u = ctx.createUnmarshaller();
        XMLInputFactory f = XMLInputFactory.newInstance();
        f.setProperty(XMLInputFactory.SUPPORT_DTD, false);
        XMLStreamReader r = f.createXMLStreamReader(new StringReader(xml));
        int count = 0;
        BigDecimal total = BigDecimal.ZERO;
        while (r.hasNext()) {
            if (r.getEventType() == XMLStreamConstants.START_ELEMENT
                    && r.getLocalName().equals("item")) {
                // Item has no @XmlRootElement, so ask for it by type: the result is wrapped
                JAXBElement<Model.Item> e = u.unmarshal(r, Model.Item.class);
                Model.Item item = e.getValue();
                total = total.add(item.price.multiply(BigDecimal.valueOf(item.qty)));
                count++;
            } else {
                r.next();
            }
        }
        System.out.println("streamed " + count + " items, total value " + total);

        // What is expensive: creating the context, not marshalling
        Model.Order order = new Model.Order("o-1", "Ana");
        order.items.add(new Model.Item("p1", 2, "9.99"));
        long best = Long.MAX_VALUE;
        long bestMarshal = Long.MAX_VALUE;
        for (int run = 0; run < 4; run++) {                     // run 0 is a warm-up
            long t0 = System.nanoTime();
            for (int i = 0; i < 20; i++) {
                JAXBContext.newInstance(Model.Order.class);
            }
            long t1 = System.nanoTime();
            JAXBContext shared = JAXBContext.newInstance(Model.Order.class);
            long t2 = System.nanoTime();
            for (int i = 0; i < 20; i++) {
                Marshaller m = shared.createMarshaller();
                m.marshal(order, new StringWriter());
            }
            long t3 = System.nanoTime();
            if (run > 0) {
                best = Math.min(best, (t1 - t0) / 20);
                bestMarshal = Math.min(bestMarshal, (t3 - t2) / 20);
            }
        }
        System.out.printf("JAXBContext.newInstance:           %,8d us each%n", best / 1000);
        System.out.printf("createMarshaller + marshal (small): %,7d us each%n",
                bestMarshal / 1000);
    }
}

Output of the streaming and cost run:

Output
streamed 50000 items, total value 7600000.00
JAXBContext.newInstance:              2,408 us each
createMarshaller + marshal (small):      84 us each
  • The StAX loop moves to each <item> start tag and calls unmarshal(reader, Item.class), which consumes that element and leaves the reader on the event after it. That is why the loop only calls next() when it did not unmarshal, the same rule as on the StAX page.
  • Item has no @XmlRootElement, so unmarshalling by declared type returns a JAXBElement<Item>; getValue() gives the object. The 50,000 items were totaled without ever holding more than one in memory.
  • Creating a context for even this two-class model took well over a millisecond, many times the cost of creating a marshaller and writing a small order. With models of hundreds of generated classes, context creation takes far longer. Create the context once, at start-up, and share it.

Choosing JAXB or a parser

When JAXB fits
SituationBetter choice
The XML has a fixed structure that maps to classes (configs, SOAP payloads, data exchange formats with an XSD)JAXB
Classes should be generated from an existing XSDJAXB with the xjc tool or a Maven plugin
Very large files that do not fit in memoryStAX, optionally unmarshalling one element at a time from the reader
Picking a few values out of arbitrary XMLXPath over DOM
Free-form documents where structure variesDOM
Subclasses in a list, XML you designJAXB with @XmlElements
Subclasses in a list, format fixed by a schemaJAXB with @XmlSeeAlso and xsi:type, as the schema requires
Untrusted inputJAXB with a schema and a StAX reader that has DTDs off