Java EE / Jakarta EE

XML in Java: SAX, DOM, StAX and Jakarta XML Binding (JAXB 4)

Intermediate7 min readUpdated

XML is still the format of many enterprise integrations, configuration files and document standards, and Java offers three parsing models plus a binding framework for it. This guide compares DOM, SAX and StAX with working examples, explains schema validation and XPath, shows how Jakarta XML Binding (JAXB) maps classes to XML in both directions since its removal from the JDK, and details the parser hardening every XML-consuming application needs.

What you will learn

  • Choose between DOM, SAX and StAX for a given document size and access pattern
  • Parse, navigate and write XML with the JAXP APIs in the java.xml module
  • Validate documents against an XML Schema and query them with XPath
  • Marshal and unmarshal Java classes with Jakarta XML Binding 4 annotations and generate classes from a schema
  • Configure every parser to prevent XML External Entity (XXE) and entity-expansion attacks

JSON won the web, but XML never left the enterprise. It arrives as SOAP envelopes, bank statement files, industry-standard messages, SAML assertions, office documents and the configuration of the application server itself, and it usually arrives from outside your trust boundary. Java's standard library has parsed XML since 2002 through JAXP (the Java API for XML Processing, now the java.xml module), which offers three models: a tree in memory, a stream of events pushed to you, or a stream of events you pull. On top of those, Jakarta XML Binding (JAXB) maps XML directly to Java classes, so that most application code never sees an element at all. This guide covers all four and — because XML parsers are a well-known attack surface — the settings that make them safe.

Three parsing models

DOMSAXStAX
ModelWhole document as an in-memory treePush: parser calls your handler for each eventPull: you ask the reader for the next event
MemoryProportional to document size (several times the bytes)ConstantConstant
AccessRandom; navigate, modify, write backForward only, read onlyForward only; separate writer API
EaseEasiest for small documentsHardest: state machine in callbacksLinear code, easy to stop or delegate
Use it forConfiguration, small messages, documents you edit or query with XPathVery large files, extracting a few values, legacy codeLarge files, streaming transforms, writing XML by hand

All three come from factories in javax.xml.parsers and javax.xml.stream. The javax.xml packages are Java SE, not Jakarta EE, and did not move to jakarta.*; only the binding API did.

DOM: the tree

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.*;

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);  // no DTD, no XXE
factory.setExpandEntityReferences(false);

Document doc = factory.newDocumentBuilder().parse(new File("orders.xml"));
NodeList lines = doc.getElementsByTagNameNS("urn:shop:orders", "line");
for (int i = 0; i < lines.getLength(); i++) {
    Element line = (Element) lines.item(i);
    String sku = line.getAttribute("sku");
    int qty = Integer.parseInt(line.getElementsByTagNameNS("urn:shop:orders", "qty").item(0).getTextContent());
}

The W3C DOM API is verbose — NodeList is not iterable, text is a child node rather than a property, whitespace between elements shows up as text nodes — but it gives you the whole document to walk, modify (createElementNS, appendChild, removeChild) and serialise back with a Transformer. Always set setNamespaceAware(true): the default is false for historical reasons, and without it namespace-qualified lookups silently return nothing.

SAX: push events

A SAX parser reads the document once and calls methods on a ContentHandler — startElement, characters, endElement — as it goes. Your handler keeps whatever state it needs:

import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;

class TotalQuantityHandler extends DefaultHandler {
    private final StringBuilder text = new StringBuilder();
    private boolean inQty;
    long total;

    @Override public void startElement(String uri, String local, String qName, Attributes atts) {
        inQty = "qty".equals(local);
        text.setLength(0);
    }
    @Override public void characters(char[] ch, int start, int length) {
        if (inQty) text.append(ch, start, length);     // may be called several times per element
    }
    @Override public void endElement(String uri, String local, String qName) {
        if (inQty) { total += Long.parseLong(text.toString().trim()); inQty = false; }
    }
}

SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
spf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
var handler = new TotalQuantityHandler();
spf.newSAXParser().parse(new File("orders.xml"), handler);

The detail that breaks naive handlers: characters can deliver the text of one element in several chunks, so you must accumulate and read the result in endElement. SAX is the fastest and leanest model and the one under most other parsers, but the inverted control makes anything beyond simple extraction awkward.

StAX: pull events

StAX (javax.xml.stream) turns the stream around: you call next() and inspect the event. The same extraction reads top to bottom:

import javax.xml.stream.*;

XMLInputFactory xif = XMLInputFactory.newInstance();
xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);                       // XXE hardening
xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);

long total = 0;
try (var in = new FileInputStream("orders.xml")) {
    XMLStreamReader r = xif.createXMLStreamReader(in);
    while (r.hasNext()) {
        if (r.next() == XMLStreamConstants.START_ELEMENT && "qty".equals(r.getLocalName())) {
            total += Long.parseLong(r.getElementText());   // reads the text and consumes the end tag
        }
    }
    r.close();
}

XMLStreamWriter is the matching writer: writeStartElement, writeAttribute, writeCharacters, writeEndElement, with escaping handled for you. Building XML by string concatenation is how invalid documents and injection bugs happen; use the writer, the DOM, or JAXB.

Validation, XPath and transformation

XML Schema (XSD) validation checks a document's structure and types before your code trusts it. Load the schema once with a SchemaFactory, then either validate a parsed document or attach the schema to the parser factory so validation happens during parsing:

SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
sf.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
sf.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");        // no fetching of remote schemas
Schema schema = sf.newSchema(new File("orders.xsd"));
schema.newValidator().validate(new StreamSource(new File("orders.xml")));  // throws SAXException on violation

XPath (javax.xml.xpath) queries a DOM: xpath.evaluate("sum(//o:line/o:qty)", doc) with a NamespaceContext mapping the o prefix. It is the quickest way to pull a few values out of a document you already have in memory, and the slowest way to process a large one, because each evaluation walks the tree. XSLT through javax.xml.transform converts XML to XML, HTML or text; the same Transformer with no stylesheet serialises a DOM to a stream, which is how you write a modified document back out.

Jakarta XML Binding

For structured documents with a known shape, dealing with elements at all is wasted effort. JAXB maps a class hierarchy to XML so that reading a document is one method call and writing is another.

Where the library lives now

JAXB was bundled in the JDK from Java 6 to Java 10 and removed in Java 11 by JEP 320, together with JAX-WS and the other Java EE modules. On any current JDK it is an ordinary dependency, and since Jakarta EE 9 the package is jakarta.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>     <!-- the reference runtime; scope runtime -->
  <version>4.0.5</version>
  <scope>runtime</scope>
</dependency>

XML Binding 4.0 is an optional part of the Jakarta EE 10 platform and absent from the Web Profile, so check whether your server ships it — the full-platform servers generally do — and otherwise add the dependency to the application. Older code importing javax.xml.bind needs its imports rewritten and the artifacts swapped; the API is otherwise identical.

Annotating classes

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import jakarta.xml.bind.annotation.*;
import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

@XmlRootElement(name = "order", namespace = "urn:shop:orders")
@XmlAccessorType(XmlAccessType.FIELD)          // map fields, ignore getters: predictable and no setter needed
@XmlType(propOrder = { "reference", "placed", "lines" })
public class OrderDocument {

    @XmlAttribute(required = true)
    String id;

    @XmlElement(required = true)
    String reference;

    @XmlElement
    @XmlJavaTypeAdapter(LocalDateAdapter.class)   // java.time is not built in; adapter converts to/from text
    LocalDate placed;

    @XmlElementWrapper(name = "lines")
    @XmlElement(name = "line")
    List<Line> lines = new ArrayList<>();

    @XmlTransient
    BigDecimal cachedTotal;                        // not part of the document

    public static class Line {
        @XmlAttribute String sku;
        @XmlElement int qty;
        @XmlElement BigDecimal unitPrice;
    }
}

A few rules drive most of the mapping. Every bound class needs a no-argument constructor. @XmlRootElement marks the classes that can be a document root; nested types need only be reachable. Without @XmlAccessorType(FIELD) JAXB binds JavaBean properties, which means every field needs a getter and a setter and a class with both a field and a property of the same name maps it twice. @XmlElementWrapper gives collections an enclosing element (<lines><line/><line/></lines>); without it, repeated <line> elements sit directly under the parent. XmlAdapter subclasses handle any type JAXB does not know, including java.time, which — unlike JPA and JSON-B — it still does not support natively.

Marshalling and unmarshalling

import jakarta.xml.bind.*;
import javax.xml.stream.XMLInputFactory;
import javax.xml.transform.stream.StreamSource;

JAXBContext context = JAXBContext.newInstance(OrderDocument.class);   // expensive: create once, it is thread-safe

// Writing
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
marshaller.marshal(order, new File("order-42.xml"));

// Reading, through a hardened StAX reader so no DTD is ever processed
XMLInputFactory xif = XMLInputFactory.newInstance();
xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
var reader = xif.createXMLStreamReader(new StreamSource(new File("incoming.xml")));

Unmarshaller unmarshaller = context.createUnmarshaller();
unmarshaller.setSchema(schema);                                         // validate while unmarshalling
OrderDocument incoming = (OrderDocument) unmarshaller.unmarshal(reader);

JAXBContext builds the mapping model by reflection and is the costly object; Marshaller and Unmarshaller are cheap and not thread-safe, so create one per operation. Set a Schema on the unmarshaller when a schema exists — without it JAXB silently ignores unknown elements and accepts missing required ones, which is convenient for lenient readers and dangerous for anything that matters. unmarshal with JAXBElement handling (unmarshal(source, OrderDocument.class)) covers documents whose root element has no @XmlRootElement class.

Generating classes from a schema

When the schema comes first — an industry standard, a partner contract — generate the classes with xjc, the schema compiler shipped with the JAXB runtime distribution and available through Maven plugins. It produces one class per complex type, an ObjectFactory with factory methods, and package-info.java with the namespace. The reverse, schemagen, derives an XSD from annotated classes. Generated code should be treated as a build output, regenerated from the schema and never edited by hand; customisations go in a binding file (.xjb) that renames classes, maps types or attaches adapters.

Hardening every parser

An XML parser will, by default, do what the document tells it to. A document can declare an external entity that points to a local file or an internal URL, and when the parser expands it the file contents end up in your data or the request goes out from your server — the XXE vulnerability, still listed under security misconfiguration in the OWASP Top 10. A document can also define entities that expand exponentially (the "billion laughs" attack) and exhaust memory. The defence is the same everywhere: refuse DTDs, and if you cannot, refuse external entities and external DTD/schema access.

ParserSetting
DocumentBuilderFactory, SAXParserFactorysetFeature("http://apache.org/xml/features/disallow-doctype-decl", true); otherwise external-general-entities and external-parameter-entities features to false, setXIncludeAware(false), setExpandEntityReferences(false)
XMLInputFactory (StAX)SUPPORT_DTD to false, IS_SUPPORTING_EXTERNAL_ENTITIES to false
SchemaFactory, TransformerFactory, ValidatorACCESS_EXTERNAL_DTD, ACCESS_EXTERNAL_SCHEMA, ACCESS_EXTERNAL_STYLESHEET to ""
AllXMLConstants.FEATURE_SECURE_PROCESSING to true (limits entity expansion; on by default since Java 7 but set it explicitly)
JAXBUnmarshal through a hardened StAX or SAX source rather than from a File or InputStream directly

Since Java 9 these limits can also be set JVM-wide in $JAVA_HOME/conf/jaxp.properties, and the JDK's built-in parser applies FEATURE_SECURE_PROCESSING by default — but third-party parsers on the classpath (Xerces, Woodstox) replace the JDK one through the service loader, and their defaults differ. Set the features in code, on every factory, and write a test that feeds a document with a <!DOCTYPE> declaring an external entity and asserts it is rejected. Jakarta REST implementations and SOAP stacks parse XML for you; check their configuration for the same settings rather than assuming.

Common mistakes

  • Namespace-unaware parsing. getElementsByTagNameNS returns nothing and XPath with prefixes fails. Call setNamespaceAware(true) on every factory.
  • Reading characters once. Text arrives in chunks; accumulate until endElement.
  • DOM for gigabyte files. OutOfMemoryError. Stream with StAX or SAX.
  • Building XML with string concatenation. Unescaped < and & produce invalid documents and let user input inject elements. Use a writer, DOM or JAXB.
  • One Marshaller shared across threads. Corrupted output. Share the JAXBContext, create marshallers per call.
  • Unmarshalling without a schema. Silent acceptance of broken documents. Set the schema and handle validation errors.
  • javax.xml.bind on a modern JDK. ClassNotFoundException at runtime. Add the Jakarta artifacts and rewrite imports.
  • Default parser settings on untrusted input. XXE and entity expansion. Harden every factory and test it.

Key takeaways

  • JAXP in the java.xml module offers DOM (tree, random access, memory-heavy), SAX (push events, minimal memory, awkward control flow) and StAX (pull events, linear code, plus a writer).
  • Use DOM for small documents you query or edit, StAX for anything large or streamed, and SAX mainly when maintaining existing code.
  • Validate untrusted documents against a schema, and use XPath for ad-hoc extraction from documents already in memory.
  • Jakarta XML Binding 4 maps classes to XML with @XmlRootElement, @XmlElement, @XmlAttribute and adapters; it lives in jakarta.xml.bind as a separate dependency since JEP 320 removed it from the JDK.
  • Share one JAXBContext, create a Marshaller or Unmarshaller per operation, set a schema when unmarshalling, and generate classes with xjc when the schema comes first.
  • Harden every parser factory against XXE — disallow DTDs, block external entities and external DTD/schema access — and unmarshal through a hardened source.

Sources and further reading

Frequently asked questions

Why does my JAXB code fail with ClassNotFoundException on Java 11 or later?
JAXB was part of the JDK from Java 6 to Java 10 as javax.xml.bind and was removed in Java 11 by JEP 320. Add it as a dependency: for the current Jakarta line, jakarta.xml.bind:jakarta.xml.bind-api (4.0.x) plus the runtime org.glassfish.jaxb:jaxb-runtime, and change imports to jakarta.xml.bind. The old javax.xml.bind 2.3 artifacts still work on modern JDKs but are no longer maintained.
When should I use SAX instead of DOM?
When the document is large relative to memory, when you only need to extract some values, or when you process a stream that never ends. DOM builds the entire tree in memory — typically several times the file size — and gives random access; SAX and StAX read forward once with constant memory. For most documents under a few megabytes DOM's convenience wins; for feeds, exports and uploads of unknown size, stream.
Is XML still relevant when everything is JSON?
In enterprise integration, yes. SOAP services, banking and insurance standards, industry schemas, office documents, Maven and application-server configuration, SAML assertions and many partner interfaces are XML. Knowing how to parse it safely matters more, not less, now that it is often handled by developers who rarely see it.
What is the difference between StAX and SAX?
Both stream. SAX pushes events into callbacks you implement, so the parser drives the flow and your code keeps state between callbacks. StAX lets your code pull the next event when it wants it, which keeps parsing logic linear and makes it easy to stop early or hand the reader to another method. StAX also has a writer API; SAX is read-only.