Java Reference
In-Depth Information
This processing—the default way to process the XML document—will reread the schema
each time a new document is parsed, even if the parser itself is being reused. For additional
performance, consider reusing schemas.
Reusing schemas provides an important benefit even when the schema is loaded from the
filesystem. When loaded, the schema must itself be parsed and processed (it is an XML doc-
ument, after all). Saving the results of this processing it and reusing it will give a big boost to
XML processing. This is particularly true in the most common use case: that the application
receives and processes thousands of XML documents, all of which conform to the same (set
of) schema(s).
There are two options for reusing a schema. The first option (which works only for the SAX
parser) is to create schema objects and associate them with the parser factory:
SchemaFactory sf = SchemaFactory . newInstance (
StreamSource ss = new
new StreamSource ( rp . getSchemaFileName ());
Schema schema = sf . newSchema ( new
new Source []{ ss });
SAXParserFactory spf = SAXParserFactory . newInstance ();
spf . setValidating ( false
false );
spf . setNamespaceAware ( true
true );
spf . setSchema ( schema );
parser = spf . newSAXParser ();
Note that the setValidating() method is called with a parameter of false in this case. The
setSchema() and setValidating() methods are mutually exclusive ways of performing
schema validation.
The second option for reusing schema objects is to use an instance of the Validator class.
That allows parsing to be separated from validation, so the two operations can be performed
at different times. When used with the StAX parser, this also allows validation to be per-
formed during parsing by embedding a special reader into the validation stream.
To use a Validator , first create that special reader. The logic of the reader is the same as be-
fore: it looks for the itemID start element and saves those IDs when they are found.
However, it must do this by acting as a delegate to a default StAX stream reader:
private class
class MyXMLStreamReader
MyXMLStreamReader extends
extends StreamReaderDelegate () {
XMLStreamReader reader ;
public MyXMLStreamReader ( XMLStreamReader xsr ) {
reader = xsr ;
Search WWH ::

Custom Search