Programming with SAX

| Questions |
| Creating a SAX Parser Incomplete character data is received via SAX Ignorable Whitespace and XML Schemas Attributes and ContentHandler.startElement Namespace of xmlns attributes Encodings and XML Version via SAX
| Answers |
| How do I create a SAX parser? |
| You can create a SAX parser by using the Java APIs for XML Processing (JAXP). The following source code shows how:
    import java.io.IOException;
    import javax.xml.parsers.FactoryConfigurationError;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.DefaultHandler;

      ...

    String xmlFile = "file:///xerces-2_11_0/data/personal.xml";
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setNamespaceAware(true);
        SAXParser parser = factory.newSAXParser();
        DefaultHandler handler = /* custom handler class */;
        parser.parse(xmlFile, handler);
    }
    catch (FactoryConfigurationError e) {
        // unable to get a document builder factory
    }
    catch (ParserConfigurationException e) {
        // parser was unable to be configured
    catch (SAXException e) {
        // parsing error
    }
    catch (IOException e) {
        // i/o error
    }
| Why does the SAX parser lose some character data or why is the data split into several chunks? |
| If you read the SAX documentation, you will find that SAX may deliver contiguous text as multiple calls to `characters`, for reasons having to do with parser efficiency and input buffering. It is the programmer's responsibility to deal with that appropriately, e.g. by accumulating text until the next non-characters event. Xerces will split calls to `characters` at the end of an internal buffer, at a new line and also at a few other boundaries. You can never rely on contiguous text to be passed in a single characters callback.
| Why doesn't the SAX parser report ignorable whitespace for XML Schemas? |
| SAX is very clear that ignorableWhitespace is only called for element content whitespace, which is defined in the context of a DTD. The result of schema validation is the Post-Schema-Validation Infoset (PSVI). Schema processors augment the base Infoset by adding new properties to element and attribute information items, but not character information items. Schemas do not change whether a character is element content whitespace.
| Why is the Attributes parameter passed to startElement always a reference to the same object? |
| Outside the scope of `startElement`, the value of the `Attributes` parameter is undefined. For each instance of Xerces' SAX parser, there exists only one `Attributes` instance which is reused for every new set of attributes. Before each `startElement` callback, the previous values in this object will be overwritten. This is done for performance reasons in order to reduce object creation. To persist a set of attributes beyond `startElement` the object should be cloned, for instance by using `org.xml.sax.helpers.AttributesImpl`.
| Why does the SAX parser report that xmlns attributes have no namespace? |
| An erratum for the Namespaces in XML Recommendation put namespace declaration attributes in the namespace "http://www.w3.org/2000/xmlns/". By default, SAX2 (SAX 2.0.2) follows the original Namespaces in XML Recommendation, so conforming parsers must report that these attributes have no namespace. To configure the parser to report a namespace for such attributes, turn on the xmlns-uris feature. When using Xerces 2.6.2 (or prior) or other parser implementations that do not support this feature, your code must handle this discrepancy when interacting with APIs such as DOM and applications which expect a namespace for xmlns attributes.
| Is there any way I can determine what encoding an entity was written in, or what XML version the document conformed to, if I'm using SAX? |
| Yes. As of SAX 2.0.2 encoding and version information is made available through the `org.xml.sax.ext.Locator2` interface. In Xerces, instances of the SAX `Locator` interface passed to a `setDocumentLocator` call will also implement the `Locator2` interface. You can determine the encoding and XML version of the entity currently being parsed by calling the `getEncoding()` and `getXMLVersion()` methods.

Copyright © 1999-2010 The Apache Software Foundation. All Rights Reserved.