Gotcha!
As you get into the more advanced features of SAX, you certainly don’t reduce the number of problems you can get yourself into. However, these problems often become more subtle, which makes for some tricky bugs to track down. I’ll point out a few of these common problems.
Return Values from an EntityResolver
As I mentioned in the section on EntityResolvers,
you should always ensure that you return null as a
starting point for resolveEntity( )
method implementations. Luckily, Java
ensures that you return something from the method, but I’ve
often seen code like this:
public InputSource resolveEntity(String publicID, String systemID)
throws IOException, SAXException {
InputSource inputSource = new InputSource( );
// Handle references to online version of copyright.xml
if (systemID.equals(
"http://www.newInstance.com/javaxml2/copyright.xml")) {
inputSource.setSystemId(
"file:///c:/javaxml2/ch04/xml/copyright.xml");
}
// In the default case, return null
return inputSource;
}As you can see, an InputSource is created
initially and then the system ID is set on that source. The problem
here is that if no if blocks are entered, an
InputSource with no system or public ID, as well
as no specified Reader or
InputStream, is returned. This can lead to
unpredictable results; in some parsers, things continue with no
problems. In other parsers, though, returning an empty
InputSource results in entities being ignored, or
in exceptions being thrown. In other words, return
null at the end of ...