Java and XML Basics, Part 3 - ErrorHandler
(Page 7 of 9 )
Now let's return to the error message we have just seen - it mentions something about an ErrorHandler and a setErrorHandler function. Looking through the DocumentBuilder class documentation, we find indeed such a function and the docco says:
public abstract void setErrorHandler(ErrorHandler eh)
Specify the ErrorHandler to be used to report errors present in the XML document to be parsed. Setting this to null will result in the underlying implementation using it's own default implementation and behavior.
Parameters:
eh - The ErrorHandler to be used to report errors present in the XML document to be parsed.
Now, at this point you have probably spotted the analogy with the SAX parsing, and you have probably remembered the error and fatalError functions we have written in the SimpleSAXParser classes. It is the same ErrorHandler interface that the DefaultHandler class implements in SAX and it is the actual class (interface) that is to receive notifications from the parser in case of warnings, errors and fatal errors.
Let's modify now our code (ValidatingDOMParser.java) and add an ErrorHandler and assign it to the parser:
/**
* Next, using the factory we create a DOM parser
*/
try
{
builder = factoryBuilder.newDocumentBuilder();
}
catch( ParserConfigurationException pce )
{
System.err.println( "Error creating DOM parser:" );
pce.printStackTrace();
System.exit( 4 );
}
/**
* Set the error handler
*/
builder.setErrorHandler( new DOMErrorHandler() );
... ... ...
/**
* XML parsing/validating error handler
*/
static class DOMErrorHandler implements ErrorHandler
{
/**
* Error -- more than likely a validation error;
* which means our XML is invalid and we should stop execution
*/
public void error( SAXParseException exception )
{
System.out.println( "Validation error: " + exception.getMessage() );
System.out.println( "Execution will stop." );
System.exit( 1 );
}
/**
* Fatal error -- execution should stop!
*/
public void fatalError( SAXParseException exception )
{
System.out.println( "FATAL error: " + exception.getMessage() );
System.out.println( "Execution will stop." );
System.exit( 1 );
}
/**
* Warning, execution can continue, the user could be warned though
*/
public void warning( SAXParseException exception )
{
System.out.println( "Warning: " + exception.getMessage() );
}
}
If we run this code, we will get the following:
java -classpath "%CLASSPATH%;." ValidatingDOMParser2 employee.xml
Validation error: Attribute value for "name" is #REQUIRED.
Execution will stop.
Next: Validating Parsers - SAX >>
More XML Articles
More By Liviu Tudor