SyntaxStudy
Sign Up
XML XML Parsing in Java: DOM and SAX
XML Beginner 2 min read

XML Parsing in Java: DOM and SAX

Java's standard library provides two complete XML parsing APIs in the javax.xml.parsers package. The DocumentBuilder class implements a DOM parser that builds a complete org.w3c.dom.Document tree in memory. You obtain a DocumentBuilder via DocumentBuilderFactory.newInstance(), configure the factory (setNamespaceAware(true), setValidating(true) if needed), then call factory.newDocumentBuilder(). Parsing a file or input stream returns a Document from which you can navigate using getDocumentElement(), getElementsByTagName(), getAttribute(), and getChildNodes(). The SAXParser class provides the Java SAX2 implementation. You obtain a SAXParser via SAXParserFactory.newInstance() (again calling setNamespaceAware(true) before newSAXParser()), then call parser.parse() with a File or InputStream and your DefaultHandler subclass. DefaultHandler implements all four handler interfaces (ContentHandler, ErrorHandler, DTDHandler, EntityResolver) with empty default methods, so you only override what you need. The startElement callback receives the namespace URI, local name, and qualified name separately when namespace awareness is enabled. Since Java 5, the StAX (Streaming API for XML) API provides a third option: a pull parser where the application drives the iteration rather than being driven by callbacks. XMLStreamReader iterates over events with nextEvent(), giving the feel of a SAX parser but with simpler state management because the application controls the loop. For XPath queries against a DOM tree, Java provides the javax.xml.xpath.XPath interface that evaluates XPath expressions and returns results as strings, node-sets (NodeList), booleans, or numbers.
Example
// Java: DOM parsing with DocumentBuilder

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.*;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;

public class DomParserExample {

    static final String XML = """
        <?xml version="1.0" encoding="UTF-8"?>
        <library>
            <book id="b001" category="fiction">
                <title>The Great Gatsby</title>
                <author>F. Scott Fitzgerald</author>
                <year>1925</year>
                <price>12.99</price>
            </book>
            <book id="b002" category="non-fiction">
                <title>Clean Code</title>
                <author>Robert C. Martin</author>
                <year>2008</year>
                <price>35.00</price>
            </book>
        </library>""";

    public static void main(String[] args) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        // Disable XXE for security
        factory.setFeature(
            "http://apache.org/xml/features/disallow-doctype-decl", true);

        DocumentBuilder builder = factory.newDocumentBuilder();
        byte[] bytes = XML.getBytes(StandardCharsets.UTF_8);
        Document doc = builder.parse(new ByteArrayInputStream(bytes));

        NodeList books = doc.getElementsByTagName("book");
        for (int i = 0; i < books.getLength(); i++) {
            Element book = (Element) books.item(i);
            String id       = book.getAttribute("id");
            String category = book.getAttribute("category");
            String title    = book.getElementsByTagName("title")
                                   .item(0).getTextContent();
            String author   = book.getElementsByTagName("author")
                                   .item(0).getTextContent();
            System.out.printf("[%s] %s by %s (%s)%n",
                              id, title, author, category);
        }
    }
}

This is the last lesson in this section.

Create a free account to earn a certificate