http://xml.apache.org/http://www.apache.org/http://www.w3.org/

Readme
Installation

API Docs
Samples
Schema

Properties
Features
FAQs

Releases
Caveats
Feedback

Y2K Compliance

Questions
 

Answers
 
How do I construct a parser in Xerces?
 

There are two ways the parser classes can be instantiated: The first way is to create a string containing the fully qualified name of the parser class. Pass this string to the org.xml.sax.helpers.ParserFactory.makeParser() method to instantiate it. This method is useful if your application will need to switch between different parser configurations. The code snippet shown below is using this method to instantiate a DOMParser.

import org.xml.sax.Parser;
import org.xml.sax.helpers.ParserFactory; 
import org.apache.xerces.parsers.DOMParser;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import java.io.IOException; 

  ...

String parserClass = "org.apache.xerces.parsers.DOMParser";

String xmlFile = "file:///Xerces-J/data/personal.xml"; 

Parser parser = ParserFactory.makeParser(parserClass);

try {
    parser.parse(xmlFile);
} catch (SAXException se) {
    se.printStackTrace();
} catch (IOException ioe) {
	ioe.printStackTrace();
}
// The next line is only for DOM Parsers

Document doc = ((DOMParser) parser).getDocument(); 

  ...
	 

The second way to instantiate a parser class is to explicitly instantiate the parser class, as shown in this example, which is creating a DOM Parser. Use this way when you know exactly which parser configuration you need, and you are sure that you will not need to switch configurations.

import org.apache.xerces.parsers.DOMParser;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import java.io.IOException;

  ...

String xmlFile = "file:///Xerces-J/data/personal.xml"; 

DOMParser parser = new DOMParser();

try {
    parser.parse(xmlFile);

} catch (SAXException se) {
    se.printStackTrace();
} catch (IOException ioe) {
    ioe.printStackTrace();
}
// The next line is only for DOM Parsers
Document doc = parser.getDocument();

  ...
	 

Once you have the Document object, you can call any method on it as defined by the DOM specification.


How do I create a DOM parser?
 

Use one of the methods in the question above, and use org.apache.xerces.parsers.DOMParser as the name of the class.

To access the DOM tree, you can call the getDocument() method on the parser instance.


How do I create a SAX parser?
 

Use one of the methods in the question above, and use org.apache.xerces.parsers.SAXParser as the name of the class.

Once you have the parser instance, you can use the standard SAX methods to set the various handlers provided by SAX.


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 now uses a DOM implementation that can take advantage of lazy evaluation to improve performance. The setNodeExpansion call on these classes controls the use of lazy evaluation. There are two values for the argument to setNodeExpansion: FULL and DEFERRED(the default).

If node expansion is set to FULL, then the DOM classes behave as they always have, creating all nodes in the DOM tree by the end of parsing.

If node expansion is set to DEFERRED, nodes in the DOM tree are only created when they are accessed. This means that a call to getDocument will return a DOM tree that consists only of the Document node. When your program accesses a child of Document, the children of the Document node will be created. All 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. This also increases the time it takes to access a node that has not been created. After nodes have been created, they are cached, so this overhead only occurs on the first access to a Node.


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 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 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.


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.

How do I access the DOM Level 2 functionality
 

Because the DOM Level 2 spec is not frozen yet, the interfaces for DOM Level 2 can be found in the package org.apache.xerces.domx and its subpackages.


How do I read data from a stream as it arrives?
 

For performance reasons, all the standard Xerces processing uses readers which buffer the input. In order to read data from a stream as it arrives, you need to instruct Xerces to use the StreamingCharReader class as its reader. To do this, create a subclass of org.apache.xerces.readers.DefaultReaderFactory and override createCharReader and createUTF8Reader as shown below.

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, and be sure to wrap the InputStream that you are reading from with an InputStreamReader.

InputStream in = ... ;
SAXParser p = new SAXParser();
DocumentHandler h = ... ;
// set the correct reader factory
p.setReaderFactory(((StreamingSAXClient)h).new StreamingCharFactory());
p.setDocumentHandler(h);

// be sure to wrap the input stream in an InputStreamReader.
p.parse(new InputSource(new InputStreamReader(in)));
		



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