Java Reference
In-Depth Information
}catch(ParserConfigurationException e){// Thrown if a parser cannot be created
// that is consistent with the
e.printStackTrace(System.err); // configuration in spf
System.exit(1);
} catch(SAXException e) { // Thrown for any other error
e.printStackTrace(System.err);
System.exit(1);
}
System.out.println("Parser object is: "+ parser);
}
}
When I ran this I got the output:
Parser will not be namespace aware
Parser will not validate XML
Parser object is: org.apache.xerces.jaxp.SAXParserImpl@fd13b5
How It Works
The output shows that the default configuration for the SAX parser produced by our
SAXParserFactory
object,
spf
, will be neither namespace aware nor validating. The parser supplied
with the SDK is one that was first developed by Sun and was subsequently donated to the XML Apache
Project. It is referred to by the name
Crimson
. You can find information on the advantages and
limitations of this particular SAX parser on the
http://xml.apache.org
web site.
The code to create the parser works as we have already discussed. Once we have an instance of the
factory method we use that to create an object encapsulating the parser. Although the reference is
returned as type
SAXParser
, the object is of type
SAXParserImpl
, which is a concrete
implementation of the abstract
SAXParser
class for a particular parser.
The Crimson parser is capable of validating XML and can be namespace aware. All we need to do is to
specify which of these options we require by calling the appropriate method. We can set the parser
configuration for the factory object,
spf
, so that we get a validating and namespace aware parser by
adding two lines to the program:
// Create factory object
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
spf.setValidating(true);
If you compile and run the code again, you should get output something like:
Parser will be namespace aware
Parser will validate XML
Parser object is: org.apache.xerces.jaxp.SAXParserImpl@13582d
We arrive at a
SAXParser
instance without tripping any exceptions and we clearly now have a
namespace aware and validating parser.