Java and XML Basics, Part 3 - Validating Parsers - SAX
(Page 8 of 9 )
After seeing the above example, I suppose you have all guessed that turning on validation in SAX is similar, and you are all looking at the setValidating function member in the SAXParserFactory. Indeed, is just as simple, and since we already implement the ErrorHandler in our class, we don't have to supply a separate ErrorHandler at parse time (ValidatingSAXParser.java - based on SimpleSAXParser2.java):
/**
* First instantiate a new factory which we'll use
* to create the SAX parser
*/
try
{
factorySAX = SAXParserFactory.newInstance();
}
catch( FactoryConfigurationError fce )
{
System.err.println( "Error creating SAX parser factory:" );
fce.printStackTrace();
System.exit( 3 );
}
/**
* Require validation
*/
factorySAX.setValidating( true );
and the result:
java -classpath "%CLASSPATH%;." ValidatingSAXParser employee.xml
Following error occurred during parsing:
org.xml.sax.SAXParseException: Attribute value for "name" is #REQUIRED.
at org.apache.crimson.parser.Parser2.error(Unknown Source)
at org.apache.crimson.parser.Parser2.defaultAttributes(Unknown Source)
at org.apache.crimson.parser.Parser2.maybeElement(Unknown Source)
at org.apache.crimson.parser.Parser2.content(Unknown Source)
at org.apache.crimson.parser.Parser2.maybeElement(Unknown Source)
at org.apache.crimson.parser.Parser2.parseInternal(Unknown Source)
at org.apache.crimson.parser.Parser2.parse(Unknown Source)
at org.apache.crimson.parser.XMLReaderImpl.parse(Unknown Source)
at javax.xml.parsers.SAXParser.parse(Unknown Source)
at javax.xml.parsers.SAXParser.parse(Unknown Source)
at ValidatingSAXParser.main(ValidatingSAXParser.java:102)
Parsing will stop...
Next: Conclusion >>
More XML Articles
More By Liviu Tudor