Java Reference
In-Depth Information
You can now use the SAXParserFactory object to create a SAXParser object as follows:
SAXParser parser = null;
try {
parser = spf.newSAXParser();
}catch(SAXException | ParserConfigurationException e){
e.printStackTrace();
System.exit(1);
}
The SAXParser object that you create here encapsulates the parser supplied with the JDK. The
newSAXParser() method for the factory object can throw the two exceptions you are catching here. A
ParserConfigurationException is thrown if a parser cannot be created consistent with the configuration
determined by the SAXParserFactory object, and a SAXException is thrown if any other error occurs. For
example, if you call the setValidating() option and the parser does not have the capability for validat-
ing documents, SAXException will be thrown. This should not arise with the parser supplied with the JDK,
though, because it supports both of these features.
The ParserConfigurationException class is defined in the javax.xml.parsers package and the
SAXException class is in the org.xml.sax package. Now let's see what the default parser is by putting to-
gether the code fragments you have looked at so far.
TRY IT OUT: Accessing a SAX Parser
Here's the code to create a SAXParser object and output some details about it to the command line:
import javax.xml.parsers.*;
import org.xml.sax.SAXException;
public class TrySAX {
public static void main(String args[]) {
// Create factory object
SAXParserFactory spf = SAXParserFactory.newInstance();
System.out.println(
"Parser will " + (spf.isNamespaceAware() ? "" : "not ") + "be
namespace aware");
System.out.println(
"Parser will " + (spf.isValidating() ? "" : "not ") +
"validate XML");
SAXParser parser = null;
// Stores parser
reference
try {
parser = spf.newSAXParser(); // Create parser object
}catch(SAXException | ParserConfigurationException e){
e.printStackTrace();
System.exit(1);
Search WWH ::




Custom Search