Java Reference
In-Depth Information
}
System.out.println("Parser object is: " + parser);
}
}
TrySAX.java
When I ran this I got the following output:
Parser will not be namespace aware
Parser will not validate XML
Parser object is:
com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl@4c71d2
How It Works
The output shows that the default configuration for the SAX parser produced by the SAXParserFactory
object spf is neither namespace-aware nor validating. The parser supplied with the JDK is the Xerces
parser from the XML Apache Project. This parser implements the W3C standard for XML, the de
facto SAX2 standard, and the W3C DOM standard. It also provides support for the W3C standard for
XML Schema. You can find detailed information on the advantages of this particular parser on the ht-
tp://xml.apache.org website.
The code to create the parser works as I have already discussed. After you have an instance of the factory
method, you 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 Xerces parser is capable of validating XML and can be namespace-aware. All you need to do is spe-
cify which of these options you require by calling the appropriate method for the factory object. You can
set the parser configuration for the factory object spf so that you 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 the following:
Parser will be namespace aware
Parser will validate XML
Parser object is:
com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl@18e18a3
You arrive at a SAXParser instance without tripping any exceptions, and you clearly now have a
namespace-aware and validating parser. By default the Xerces parser validates an XML document with
a DTD. To get it to validate a document with an XML Schema, you need to set another option for the
parser, as I discuss in the next section.
Parser Features and Properties
Search WWH ::




Custom Search