Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 119 ยท Data Formats

XML Processing

Parse XML in Java with DOM and XPath, stream big files with StAX, write XML with Transformer, and lock down parsers against XXE attacks. JAXB notes included.

JSON took over web APIs, but XML is still everywhere in the Java world: Maven's pom.xml, Spring's older configuration, SOAP web services, office documents (a .docx file is zipped XML), RSS feeds, SVG images, bank and government data exchanges, and countless enterprise integrations. Sooner or later you will need to read or write it.

The JDK ships complete XML support in the java.xml module, so everything in this lesson runs without any library. You will parse a document into a DOM tree, query it with XPath, process large files with the StAX streaming API, write XML with a Transformer, and, most importantly, configure parsers so a malicious document can't read files from your server (the XXE attack). At the end there is a short look at JAXB, which maps XML to classes the way Jackson maps JSON.

XML in one minute

An XML document is a tree of elements. Each element has a name, optional attributes, and content: text, other elements, or both.

XML
<?xml version="1.0" encoding="UTF-8"?>
<catalog currency="EUR">
  <book id="b1" lang="en">
    <title>Patterns of Rain</title>
    <price>18.50</price>
  </book>
  <!-- comments look like this -->
</catalog>

Compared with JSON: there is exactly one root element, every opening tag needs a matching closing tag (or the self-closing form <br/>), names are case-sensitive, attribute values are always quoted, and the characters < and & must be escaped as &lt; and &amp; in text. A document that follows these rules is well-formed. A document that also matches a schema (XSD or DTD) is valid.

Java offers three styles of reading XML:

API Style Memory Good for
DOM (DocumentBuilder) Loads the whole tree Whole document in memory Small/medium files, random access, editing
SAX (SAXParser) Pushes events to your callbacks Constant Huge files (older API)
StAX (XMLStreamReader) You pull events in a loop Constant Huge files (simpler than SAX)

Parsing with DOM

DocumentBuilderFactory creates a DocumentBuilder, which parses text into a Document. From there, getDocumentElement() gives you the root, getElementsByTagName finds elements anywhere below a node, getAttribute reads attributes, and getTextContent returns all the text inside an element.

Java Reading a catalog with DOM

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Three details trip people up:

  • Entities are decoded for you. Salt &amp; Signal comes back as Salt & Signal.
  • Missing attributes return an empty string, not null. Use hasAttribute("x") when the difference matters.
  • Whitespace is content. The line breaks and indentation between elements are text nodes, so getChildNodes() returns more than the elements you see, and getFirstChild() is usually a whitespace node. Filter by getNodeType() == Node.ELEMENT_NODE, or use getElementsByTagName/XPath, which only return elements.

The DOM API dates from the late 1990s and feels clunky (NodeList isn't even Iterable). It is still the standard, and for small documents it is perfectly fine.

Querying with XPath

Walking a DOM by hand gets long quickly. XPath is a small query language for XML trees: /catalog/book[@lang='en']/title means "the titles of English books". The JDK's javax.xml.xpath package evaluates XPath 1.0 expressions on a DOM Document.

Expression Selects
/catalog/book book children of the root catalog
//title every title element anywhere
//book[@id='b2'] the book whose id attribute is b2
//book[price > 15]/title titles of books costing more than 15
//book[1] the first book (XPath counts from 1)
count(//book), sum(//price) numbers computed from the document
//book/@lang the lang attributes themselves

evaluate(expression, node, returnType) takes a return type: XPathConstants.STRING, NUMBER (a Double), BOOLEAN, NODE or NODESET (a NodeList). Compile an expression once with compile if you run it many times.

Java XPath queries on the catalog

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

count and sum return a Double, which is why the output shows 4.0 and 18.0. A query that matches nothing returns an empty string with the default STRING type, so check with BOOLEAN or a NODESET if "no match" must be handled.

If your document uses namespaces (<inv:invoice xmlns:inv="urn:example:invoice">), call factory.setNamespaceAware(true) and give the XPath a NamespaceContext that maps prefixes to URIs. Without it, prefixed expressions silently match nothing, a classic source of confusion with SOAP and Office files.

XXE: the attack every XML parser must block

XML has an old feature called a DTD (document type definition), which can declare entities: named replacements like macros. An external entity tells the parser to load its value from a URL or file. Here is a document an attacker might send to your upload endpoint:

XML
<?xml version="1.0"?>
<!DOCTYPE order [ <!ENTITY secret SYSTEM "file:///etc/passwd"> ]>
<order><note>&secret;</note></order>

A parser with default settings reads /etc/passwd and puts its contents into <note>. If your application echoes the note back ("Order received: ..."), the attacker now has your file. Variants read cloud metadata URLs, scan internal networks, or crash the server with entities that expand exponentially (the "billion laughs" attack). This class of bug, XML External Entity (XXE) injection, has its own place in the OWASP Top 10 history.

The example below creates a harmless "secret" file and shows both a default parser and a hardened one reading the same malicious document.

Java XXE: a default parser leaks a file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The default parser printed the file's contents. The hardened one refused the document as soon as it saw the DOCTYPE. The parser may print a [Fatal Error] line to standard error as well; that is the JDK's default error handler, and you can silence it with builder.setErrorHandler(...).

The rule for production code: disallow DOCTYPE declarations entirely unless you truly need DTDs, which almost no modern application does. Apply the equivalent settings to every XML entry point: DocumentBuilderFactory, SAXParserFactory, XMLInputFactory (StAX), TransformerFactory, SchemaFactory and XPath on untrusted documents. A good habit is one small factory class in your project that creates pre-hardened parsers, so nobody calls newInstance() directly. Recent JDKs are gradually tightening defaults, but don't rely on that.

Streaming large files with StAX

DOM needs the whole document in memory, often five to ten times the file size. A 2 GB export won't fit. StAX (Streaming API for XML) reads the document as a sequence of events: start element, characters, end element, and so on. You pull the next event with next() in a loop and keep only what you need, so memory use stays flat no matter how big the file is.

Java Summing a large order feed with StAX

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The loop only ever holds one event's worth of data. getElementText() is a convenient shortcut that reads all the text of the current element and moves to its end tag. For an even simpler style, XMLEventReader returns event objects instead of integer codes, at a small performance cost.

SAX, the older streaming API, does the same work with callbacks (startElement, characters, endElement) in a DefaultHandler subclass. It is just as fast but harder to write, because your state lives in fields between callbacks. Prefer StAX for new code; you will still see SAX in older projects.

Writing XML

Never build XML by gluing strings together. Sooner or later a customer named Smith & Sons produces a broken document, or worse, injected markup. The two safe options both escape special characters automatically:

  • Build a DOM and serialize it with a Transformer (from javax.xml.transform), which can indent the output. Best for small documents you assemble or edit.
  • Stream with XMLStreamWriter, writing start tags, attributes, text and end tags in order. Best for large outputs, since nothing is kept in memory.
Java Writing XML with DOM + Transformer and with StAX

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Both versions escaped & as &amp;, < as &lt; and > as &gt; (the last one is optional in text, but harmless). Also notice that the DOM output lists qty before sku: attributes have no defined order in XML, and the JDK's serializer writes them alphabetically, so never write code that depends on attribute order. The indent-amount property is specific to the JDK's built-in transformer (based on Apache Xalan); without it, the JDK indents with zero or four spaces depending on the version. The streaming writer doesn't indent at all, which is fine for machines.

A Transformer can do much more than write files: given an XSLT stylesheet, it converts XML into other XML, HTML or text. That technology is less common today but still powers many document pipelines.

JAXB: binding XML to classes

Writing DOM code for every document type is tedious. Jakarta XML Binding (JAXB, formerly javax.xml.bind) maps XML to annotated classes, much like Jackson does for JSON. It was part of the JDK until Java 10 and was removed in Java 11; today you add it as a dependency (jakarta.xml.bind:jakarta.xml.bind-api plus an implementation such as org.glassfish.jaxb:jaxb-runtime). It isn't available on our server, so here is a read-only sketch:

Java
import jakarta.xml.bind.*;
import jakarta.xml.bind.annotation.*;

@XmlRootElement(name = "book")
@XmlAccessorType(XmlAccessType.FIELD)
public class Book {
    @XmlAttribute private String id;
    @XmlElement private String title;
    @XmlElement private BigDecimal price;
    // JAXB needs a no-argument constructor; getters/setters omitted
}

JAXBContext context = JAXBContext.newInstance(Book.class);   // create once, reuse
Book book = (Book) context.createUnmarshaller().unmarshal(new StringReader(xml));

Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(book, System.out);
// <book id="b1"><title>Patterns of Rain</title><price>18.50</price></book>

JAXB tools can also generate these classes from an XSD schema, which is the usual way to integrate with SOAP services and standardized formats. Another option, if you already use Jackson, is the jackson-dataformat-xml module, whose XmlMapper reads and writes XML with the same annotations and API as ObjectMapper.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. For <a> <b>1</b> </a> parsed with DOM, how many child nodes does <a> have?

    The whitespace before and after the b element are text nodes, so a has a text node, an element and another text node.
  2. 2. Which setting is the most effective protection against XXE in DocumentBuilderFactory?

    XXE needs a DOCTYPE to declare the external entity. Refusing DOCTYPE declarations blocks the whole class of attacks.
  3. 3. What does xpath.evaluate("count(//item)", doc, XPathConstants.NUMBER) return for a document with 3 items?

    XPath 1.0 numbers are floating-point, so NUMBER results come back as a Double.
  4. 4. You need to extract totals from a 4 GB XML export. Which API fits best?

    DOM would need several times the file size in memory. A streaming parser like StAX processes one event at a time.
  5. 5. Why is building XML with string concatenation risky?

    DOM, Transformer and XMLStreamWriter escape special characters automatically. Hand-built strings make you responsible for every value.

Summary

  • The JDK includes everything for XML: DOM (DocumentBuilder) for in-memory trees, XPath for queries, StAX and SAX for streaming, and Transformer for writing and XSLT.
  • In DOM, whitespace becomes text nodes, missing attributes are empty strings, and entities like &amp; are decoded for you.
  • XPath expressions such as //book[price > 15]/title replace long manual traversals; counting starts at 1 and numbers come back as Double.
  • XXE lets a malicious document read files or call internal URLs. Disallow DOCTYPE declarations and enable secure processing on every parser factory.
  • Use StAX for large files: memory stays flat.
  • Write XML with DOM + Transformer or XMLStreamWriter, never with string concatenation.
  • JAXB (Jakarta XML Binding) maps XML to classes; it left the JDK in Java 11 and is now a separate dependency. Jackson's XmlMapper is an alternative.

Next: CSV, Properties and Other Formats covers the simple-looking formats that hide surprising traps, and how to choose the right format for a job.