Java Reference
In-Depth Information
Features of a Parser
As we have seen, namespace awareness and whether a parser is validating or not are both features, and
these can be set by calling either
setNamespaceAware()
or
setValidating()
for the
SAXParserFactory
object, but a parser will typically have a number of other features. You can set
other features for a parser by calling the
setFeature()
method for the
SAXParserFactory
object
before you create the
SAXParser
instance. The first argument is a
String
that identifies a particular
feature and the second argument is a
boolean
value that you specify as
true
or
false
to set the
feature on or off. Of course, all features that you want must be set before you create the parser object.
You will find details of the features that a SAX parser may have at
http:/www.saxproject.org
.
Here's how we might set the parser configuration to use string interning so that fast comparisons for
string equality can be used by the parser:
try {
spf.setFeature("http://xml.org/sax/features/string-interning", true);
} catch(ParserConfigurationException e) { // Serious parser configuration error
e.printStackTrace();
System.exit(1);
} catch(SAXNotRecognizedException e) { // Feature name not recognized
e.printStackTrace();
System.exit(1);
} catch(SAXNotSupportedException e) { // Feature recognized but not supported
{
e.printStackTrace();
System.exit(1);
}
The
SAXNotRecognizedException
and
SAXNotSupportedException
classes are subclasses of
SAXException
defined in the
org.xml.sax
package. You could therefore catch either of these with
a single
catch
block for an exception object of type
SAXException
. With explicit
catch
blocks as
we have here, you would need an
import
statement for each of the class names.
There is no set collection of features for a SAX2 parser so a parser may implement any number of
arbitrary features. While it is not mandatory, there are a standard set of features that most, if not all,
SAX2 parsers are likely to support. They all have names of the form
http://xml.org/sax/features/name
,
and you can find details of these on the official web site for SAX noted earlier.
If you need to check whether a particular feature is set - you might want to check the default status for
instance -, you just call the
getFeature()
method for the
SAXParserFactory
object with a
reference to a string containing the URI for the feature. The method returns a
boolean
value
indicating the status of the feature. Note that it can throw the same exceptions as the
setFeature()
method so you have to put the call in a
try
block.