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.
💡 Tip: For most modern Java projects working with moderate-sized configuration or data files, DOM's simplicity is usually worth the extra memory — reserve SAX/StAX for genuinely large documents.