XML Parsing in Java
Estimated study time: 16 minutes.
Java's standard library ships with built-in support for all three major XML parsing approaches — DOM, SAX, and StAX — so you don't need any external dependency to get started.
DOM Parsing in Java
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File("course.xml"));
NodeList titles = doc.getElementsByTagName("title");
System.out.println(titles.item(0).getTextContent());
SAX Parsing in Java
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
parser.parse("course.xml", new DefaultHandler() {
public void startElement(String uri, String localName,
String qName, Attributes attrs) {
System.out.println("Start: " + qName);
}
});
StAX Parsing in Java
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader reader = factory.createXMLStreamReader(new FileReader("course.xml"));
while (reader.hasNext()) {
reader.next();
}
Choosing an Approach in Java
- DOM — small configuration files, or when you need to edit and rewrite the XML.
- SAX — very large files where you only need to extract specific data in a single pass.
- StAX — large files where you also want cleaner, more controllable code than SAX offers.
A Worked DOM Example with Attributes and Child Elements
Most real files contain repeating records. Given this courses.xml:
<courses>
<course id="C101" level="beginner">
<title>Java Basics</title>
<duration>40</duration>
</course>
<course id="C202" level="advanced">
<title>Spring Boot</title>
<duration>60</duration>
</course>
</courses>
the following code loops through every course element and reads both attributes and child text:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.setNamespaceAware(true);
Document doc = factory.newDocumentBuilder().parse(new File("courses.xml"));
doc.getDocumentElement().normalize();
NodeList courses = doc.getElementsByTagName("course");
for (int i = 0; i < courses.getLength(); i++) {
Element course = (Element) courses.item(i);
String id = course.getAttribute("id");
String title = course.getElementsByTagName("title").item(0).getTextContent().trim();
int hours = Integer.parseInt(
course.getElementsByTagName("duration").item(0).getTextContent().trim());
System.out.println(id + " | " + title + " | " + hours + " hours");
}
Casting each node to Element gives access to getAttribute(). Calling trim() removes the line breaks and spaces that pretty-printed XML adds around text.
Parsing Untrusted XML Safely
XML supports document type definitions and external entities. If a parser processes them from untrusted input, an attacker-controlled file could make it read local files or exhaust memory, a class of issue known as XXE. Protect your application by turning these features off before parsing anything you did not create yourself:
- For DOM and SAX factories, set
disallow-doctype-declto true as shown above. If DTDs are genuinely required, disable external general and parameter entities instead. - For StAX, set
XMLInputFactory.SUPPORT_DTDandXMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIESto false. - Enable
XMLConstants.FEATURE_SECURE_PROCESSINGto apply the JDK's built-in processing limits. - Keep the JDK updated, and follow the OWASP XXE prevention guidance for the exact settings for each parser.
Using XPath for Targeted Lookups
When you only need a few values from a DOM tree, XPath is shorter than walking nodes manually:
XPath xpath = XPathFactory.newInstance().newXPath();
String title = xpath.evaluate("/courses/course[@id='C202']/title", doc);
System.out.println(title); // Spring Boot
Typical Bugs and How to Avoid Them
| Problem | Cause | Fix |
|---|---|---|
| Text includes extra spaces | Whitespace from indentation | Call trim() or ignore whitespace nodes |
| Child nodes include text nodes | getChildNodes() returns all node types | Check getNodeType() == Node.ELEMENT_NODE |
| Namespaced elements not found | Parser not namespace aware | Call setNamespaceAware(true) and use the namespace-aware lookup methods |
| File stays locked | Streams never closed | Use try-with-resources for readers and StAX streams |
Mapping XML Straight to Objects
If your code keeps converting the same XML structure into Java objects by hand, consider a binding library instead of a low-level parser. Jakarta XML Binding (JAXB) lets you annotate a class with element and attribute names and then turn a file into objects in a couple of lines. Jackson's XML module offers a similar approach and is popular in Spring projects that already use Jackson for JSON. Binding libraries are the most readable choice for well-defined documents, while DOM, SAX and StAX remain the right tools for unknown structures, very large files or fine-grained control.
Whichever approach you pick, write a small unit test with a sample file, including a missing element and an empty value, so parsing errors are caught before real data arrives.