| Questions |
| Creating a DOM Parser Creating a SAX Parser Controlling parser options Using lazy DOM Handling Errors Controlling Entity Representation What does "non-validating" mean? Associating Data with a Node Parsing Several Documents How do I access the DOM Level 2 functionality? How do I read data from a stream as it arrives?
| Answers |
| How do I create a DOM parser? |
    import org.apache.xerces.parsers.DOMParser;
    import org.w3c.dom.Document;
    import org.xml.sax.SAXException;
    import java.io.IOException;

      ...

    String xmlFile = "file:///xerces-1_2_1/data/personal.xml";

    DOMParser parser = new DOMParser();

    try {
        parser.parse(xmlFile);

    } catch (SAXException se) {
        se.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }

    Document document = parser.getDocument();
| How do I create a SAX parser? |
    import org.apache.xerces.parsers.SAXParser;
    import org.xml.sax.Parser;
    import org.xml.sax.ParserFactory;
    import org.xml.sax.SAXException;
    import java.io.IOException;

      ...

    String xmlFile = "file:///xerces-1_2_1/data/personal.xml";

    String parserClass = "org.apache.xerces.parsers.SAXParser";
    Parser parser = ParserFactory.makeParser(parserClass);

    try {
        parser.parse(xmlFile);
    } catch (SAXException se) {
        se.printStackTrace();
    } catch (IOException ioe) {
    	ioe.printStackTrace();
    }
| How do I control the various parser options? |
| For this release, all of the parser control API's have been switched over to the SAX2 Configurable interface. This provide a uniform and extensible mechanism for setting and querying parser options. Here are guides to the set of available features and properties.
| How do I use the lazy evaluating DOM implementation? |
| The DOM parser class `org.apache.xerces.parsers.DOMParser` uses a DOM implementation that can take advantage of lazy evaluation to improve performance. There is also a mode where the parser creates all of the nodes as the document is parsed. By default, the parser uses the lazy evaluation DOM implementation. Nodes in the DOM tree are only created when they are accessed. The initial call to `getDocument()` will return a DOM tree that consists only of the Document node. All of the immediate children of a Node are created when any of that Node's children are accessed. This shortens the time it takes to parse an XML file and create a DOM tree at the expense of requiring more memory during parsing and traversing the document. The lazy evaluation feature is set using the SAX2 Configurable interface. To turn off this feature, use the following code:
    DOMParser parser = new DOMParser();
    parser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", false);
To turn the lazy evaluation feature back on, use the following code:
    parser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", true);
| How do handle errors? |
| When you create a parser instance, the default error handler does nothing. This means that your program will fail silently when it encounters an error. You should register an error handler with the parser by supplying a class which implements the `org.xml.sax.ErrorHandler` interface. This is true regardless of whether your parser is a DOM based or SAX based parser.
| How can I control the way that entities are represented in the DOM? |
| The feature `http://apache.org/xml/features/dom/create-entity-ref-nodes` controls how entities appear in the DOM tree. When this feature is set to true (the default), an occurance of an entity reference in the XML document will be represented by a subtree with an EntityReference node at the root whose children represent the entity expansion. If the property is false, an entity reference in the XML document is represented by only the nodes that represent the entity expansion. In either case, the entity expansion will be a DOM tree representing the structure of the entity expansion, not a text node containing the entity expansion as text.
| Why does "non-validating" not mean "well-formedness checking only"? |
| Using a "non-validating" parser does not mean that only well-formedness checking is done! There are still many things that the XML specification requires of the parser, including entity substitution, defaulting of attribute values, and attribute normalization. This table describes what "non-validating" really means for Xerces-J parsers. In this table, "no DTD" means no internal or external DTD subset is present.
| non-validating parsers | validating parsers
| DTD present | no DTD | DTD present | no DTD
DTD is read | Yes | No | Yes | Error
entity substitution | Yes | No | Yest | Error
defaulting of attributes | Yes | No | Yes | Error
attribute normalization | Yes | No | Yes | Error
checking against model | No | No | Yes | Error
| How do I associate my own data with a node in the DOM tree? |
| The class `org.apache.xerces.dom.NodeImpl` provides a `void setUserData(Object o)` and an `Object getUserData()` method that you can use to attach any object to a node in the DOM tree. Beware that you should try and remove references to your data on nodes you no longer use (by calling `setUserData(null)`, or these nodes will not be garbage collected until the whole document is.
| How do I more efficiently parse several documents sharing a common DTD? |
| DTDs are not currently cached by the parser. The common DTD, since it is specified in each XML document, will be re-parsed once for each document. However, there are things that you can do now, to make the process of reading DTD's more efficient: keep your DTD and DTD references local use internal DTD subsets, if possible load files from server to local client before parsing Cache document files into a local client cache. You should do an HTTP header request to check whether the document has changed, before accessing it over the network. Do not reference an external DTD or internal DTD subset at all. In this case, no DTD will be read. Use a custom `EntityResolver` and keep common DTDs in a memory buffer.
| How do I access the DOM Level 2 functionality? |
| The DOM Level 2 specification is at the stage of "Candidate Recommendation" (CR), which allows feedback from implementors before it becomes a "Recommedation". It is comprised of "core" functionality, which is mainly the DOM Namespaces implementation, and a number of optional modules (called Chapters in the spec). Please refer to: http://www.w3.org/TR/DOM-Level-2/ for the latest DOM Level 2 specification. The following DOM Level 2 modules are fully implemented in Xerces-J: Chapter 1: Core - most of these enhancements are for Namespaces, and can be acessed through additional functions which have been added directly to the org.w3c.dom.* classes. Chapter 6: Events - The org.w3c.dom.events.EventTarget interface is implemented by all `Nodes` of the DOM. The Xerces-J DOM implementation handles all of the event triggering, capture and flow. Chapter 7: Traversal - The Traversal module interfaces are located in org.w3c.dom.traversal. The `NodeIterator` and `TreeWalker`, and `NodeFilter` interfaces have been supplied to allow traversal of the DOM at a higher-level. Our DOM Document implementation class, `DocumentImpl` class now implements `DocumentTraversal`, which supplies the factory methods to create the iterators and treewalkers. Chapter 8. Range - The Range module interfaces are located in org.w3c.dom.range. The Range interface allows you to specify ranges or selections using boundary points in the DOM, along with functions (like delete, clone, extract..) that can be performed on these ranges. Our DOM Document implementation class, `DocumentImpl` class now implements `DocumentRange`, that supplies the factory method to create a `Range`.
| Since the DOM Level 2 is still in the CR phase, some changes to these specs are still possible. The purpose of this phase is to provide feedback to the W3C, so that the specs can be clarified and implementation concerns can be addressed.
| How do I read data from a stream as it arrives? |
| There are 3 problems you have to deal with: The Apache parsers read the entire data stream into a buffer before they start parsing; you need to change this behaviour, so that they analyse "on the fly" The Apache parsers terminate when they reach end-of-file; with a data stream, unless the sender drops the socket, you have no end-of-file, so you need to terminate in some other way The Apache parsers close the input stream on termination, and this closes the socket; you normally don't want this, because you'll want to send an ack to the data stream source, and you may want to have further exchanges on the socket anyway. Preventing the buffering To do this, create a subclass of org.apache.xerces.readers.DefaultReaderFactory and override createCharReader and createUTF8Reader as shown below.
    package org.apache.xerces.readers;

    import org.apache.xerces.framework.XMLErrorReporter;
    import org.apache.xerces.utils.ChunkyByteArray;
    import org.apache.xerces.utils.StringPool;
    import org.xml.sax.InputSource;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.Reader;
    import java.net.URL;
    import java.util.Stack;

    public class StreamingCharFactory extends org.apache.xerces.readers.DefaultReaderFactory {
        public XMLEntityHandler.EntityReader createCharReader(XMLEntityHandler  entityHandler,
                                                              XMLErrorReporter errorReporter,boolean sendCharDataAsCharArray,
                                                              Reader reader,
                                                              StringPool stringPool)
        throws Exception
        {
            return new org.apache.xerces.readers.StreamingCharReader(entityHandler,
                                                                     errorReporter,
                                                                     sendCharDataAsCharArray,
                                                                     reader,
                                                                     stringPool);
        }

        public XMLEntityHandler.EntityReader createUTF8Reader(XMLEntityHandler entityHandler,
                                                              XMLErrorReporter errorReporter,
                                                              boolean sendCharDataAsCharArray,
                                                              InputStream data,StringPool stringPool)
        throws Exception
        {
            XMLEntityHandler.EntityReader reader;
            reader = new org.apache.xerces.readers.StreamingCharReader(entityHandler,
                                                                       errorReporter,
                                                                       sendCharDataAsCharArray,
                                                                       new InputStreamReader(data, "UTF8"),
                                                                       stringPool);
            return reader;
        }
    }
In your program, after you instantiate a parser class, replace the DefaultReaderFactory with StreamingCharFactory. You'll need to instantiate your parser as a SAXParser, rather than simply as an XMLReader, because the XMLReader interface doesn't have the setReaderFactory method. Be sure to wrap the InputStream that you are reading from with an InputStreamReader.
    try {
        SAXParser parser =
        (SAXParser)Class.forName("org.apache.xerces.parsers.SAXParser").newInstance();
        parser.setContentHandler(new DocProcessor(out));
        parser.setReaderFactory(new StreamingCharFactory());
        parser.parse(new InputSource(bufferedReader));
    } catch (Exception ex) {
    }
Terminating the parse One way that works forSAX is to throw an exception when you detect the logical end-of-document. For instance, in your class extending DefaultHandler, you can have:
    public class DocProcessor extends DefaultHandler {
        private int level;
        .
        .
        public void startElement(String uri,
                                 String localName,
                                 String raw,
                                 Attributes attrs) throws SAXException
        {
            ++level;
        }

        public void endElement (String namespaceURI,
                                String localName,
                                String qName) throws SAXException
        {
            if ((--level) == 0) {
                throw new SAXException ("Finished");
            }
        }
Preventing the parser from closing the socket One way is to subclass BufferedReader to provide an empty close method. So, invoke the parser as follows:
        Socket socket;

        // code to set the socket

        parser.parse(new InputSource(new MyBufferedReader(new InputStreamReader(socket.getInputStream()))));
        .
        .
        class MyBufferedReader extends BufferedReader
        {
            public MyBufferedReader(InputStreamReader i) {
                super(i);
            }

            public void close() {
            }
        }