JAXP Code Samples

Parse an XML document into a DOM model

The quickest way to get started with JAXP is to load XML documents in to a DOM model. This is fine for configuration files and small documents but should be avoided for large documents as it doesn't scale well due to the memory overhead associated with DOM models.

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parseinputStream );

Implementing a SAX parser

A much smarter way to process XML documents is to use a SAX parser. This is a streaming approach where data can be processed one element at a time without the need to load the entire XML document into memory first.

This code snippet demonstrates how to use a SAX parser with JAXP.

public class MyParser {
    public void parse(InputStream isthrows ParserConfigurationExceptionSAXExceptionIOException
    {
        XMLHandler handler = new XMLHandler();
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setNamespaceAwaretrue );
        SAXParser p = factory.newSAXParser();
        p.parseishandler );
    }

    class XMLHandler extends DefaultHandler {
        // ... implement this ...
    }
}