Features and Properties

SAX uses properties and features to control parser behavior. Each feature and property has a name that’s an absolute URI. Like namespace URIs, absolute URIs are only used to name things and do not necessarily point to a real page you can load into a web browser. Features are either true or false; that is, they’re Booleans. Properties have values of an appropriate Object type. Different parsers support different groups of features and properties, although there are a few standard ones most parsers support.

The http://xml.org/sax/features/validation feature controls whether a parser validates. If this feature is true, then the parser will report validity errors in the document to the registered ErrorHandler; otherwise, it won’t. This feature is turned off by default. To turn a feature on, pass the feature’s name and value to the XMLReader’s setFeature( ) method:

try {
  parser.setFeature("http://xml.org/sax/features/validation", true);
}
catch (SAXNotSupportedException ex) {
  System.out.println("Cannot turn on validation right now.");
}
catch (SAXNotRecognizedException ex) {
  System.out.println("This is not a validating parser.");
}

Not all parsers can validate. If you try to turn on validation in a parser that doesn’t validate or set any other feature the parser doesn’t provide, setFeature( ) throws a SAXNotRecognizedException. If you try to set a feature the parser does recognize but cannot change at the current time—e.g., you try to turn on validation ...

Get XML in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.