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.
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
Everything starts with a JAXBContextMarshallerUnmarshaller
| Version | Year | What changed |
|---|---|---|
| JAXB 2.0 | 2006 | Annotation-based mapping; bundled with Java 6 as javax.xml.bind |
| JAXB 2.3 | 2017 | Last version in the JDK; deprecated in Java 9 |
| Removed from the JDK | 2018 | Java 11, JEP 320 |
| Jakarta XML Binding 3.0 | 2020 | Package renamed to jakarta.xml.bind |
| Jakarta XML Binding 4.0 | 2022 | Requires Java 11; used here with the GlassFish runtime 4.0.8 |
The default mapping (XmlAccessType.PUBLIC_MEMBERXmlAccessType.FIELD
Setup: JAXB is no longer in the JDK
JAXB shipped with Java 6 to 10 as javax.xml.bindjakarta.xml.bind
<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.newInstancejavax.xml.bindjakarta.xml.bind
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.
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);
}
}
}
| Annotation | Effect 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 |
@XmlAttribute | Written as id="o-7" |
@XmlElementWrapper(name = "items")@XmlElement(name = "item") | The list becomes <items><item/><item/></items><order> |
@XmlElement(required = true) | Marks the element as required in a generated schema; on its own it does not reject input (shown below) |
@XmlTransient | Excluded 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
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:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<order id="o-7">
<customer>Ana & 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:
- The
was escaped to& and read back as& .& - The
field was null, so nonote element was written.<note> is not in the XML at all.internalStatus - The elements follow
, and the items are inside thepropOrder wrapper.<items> - After reading back,
is "NEW" only because the field initializer ran in the no-argument constructor; JAXB never touched it.internalStatus - The incomplete document has an unknown
element, no customer, and an item with no quantity or price. JAXB accepted it without a word:<extra> is null even though it is markedcustomer , the missingrequired is 0, and the missingint is null.BigDecimal
JAXBContextMarshallerUnmarshaller
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.
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:
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.
| Input problem | Default behavior | How to make it fail |
|---|---|---|
Unknown element (<extra> | Skipped; a ValidationEvent | An event handler that returns falseUnmarshalException |
| Missing required element | Field stays null; no event at all | A schema set with setSchema |
Value that does not fit the type (qty="many" | An unchecked NumberFormatExceptionunmarshal | With a schema it becomes a validation error instead: "'many' is not a valid value for 'integer'" |
| External entity reading a file | Blocked 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
means "continue", so collecting events is a cheap way to audit input without rejecting it.true - The schema is generated from the classes with
, so it cannot drift from the model. The errorgenerateSchema sayscvc-complex-type.2.4.a arrived where<items> was required. In a real project you would usually validate against the published XSD instead.<customer> - Because
is unchecked, aNumberFormatException block does not catch it. Code that reads input it does not control should either validate with a schema or also catchcatch (JAXBException e) .RuntimeException - For the XXE test, the default unmarshal refused to read
because the GlassFish runtime restricts external access. The StAX reader with/etc/hostname 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 theSUPPORT_DTDDOM parser page for what XXE does when nothing blocks it.
Custom types with XmlAdapter
JAXB maps strings, numbers, BigDecimaljava.util.DateXMLGregorianCalendarjava.timeXmlAdapterString
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:
<shipment id="s-1"><shipped>2026-11-14</shipped></shipment>
read back: 2026-11-14 (SATURDAY), class LocalDate
JAXB_FRAGMENT<?xml ...?>LocalDate@XmlJavaTypeAdapterspackage-info.javaLocalDate
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.
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:
@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.
maps each subclass to its own element name, so the ledger contains@XmlElements and<card> , and reading back created a<transfer> and aCard . This is the more readable format and the usual choice when you design the XML.Transfer- With a single
on a base-class list, JAXB writes every entry as@XmlElement and adds<payment> orxsi:type="card" , using the subclasses listed inxsi:type="transfer" . Without@XmlSeeAlso , the context would not know the subclasses at all.@XmlSeeAlso - The namespaced root came out as
withns2:ledger . The XML is correct, but generated prefixes such asxmlns:ns2 surprise people. Ans2 withpackage-info.java chooses the prefix, or makes the namespace the default for the package.@XmlSchema(namespace = ..., xmlns = @XmlNs(prefix = "pay", ...)) - 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
that converts a record to a JAXB-friendly class.XmlAdapter
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
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:
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
start tag and calls<item> , which consumes that element and leaves the reader on the event after it. That is why the loop only callsunmarshal(reader, Item.class) when it did not unmarshal, the same rule as on thenext()StAX page . has noItem , so unmarshalling by declared type returns a@XmlRootElement ;JAXBElement<Item> gives the object. The 50,000 items were totaled without ever holding more than one in memory.getValue()- 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
| Situation | Better 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 XSD | JAXB with the xjc |
| Very large files that do not fit in memory | |
| Picking a few values out of arbitrary XML | |
| Free-form documents where structure varies | |
| Subclasses in a list, XML you design | JAXB with @XmlElements |
| Subclasses in a list, format fixed by a schema | JAXB with @XmlSeeAlsoxsi:type |
| Untrusted input | JAXB with a schema and a StAX reader that has DTDs off |