Code example for Validator

Methods: setErrorHandler, validate

0
 
  private void validateInternal(InputStream xml, URL xmlSchema) throws SAXException, IOException {
    final SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final Schema schema = sf.newSchema(xmlSchema);
    final Validator validator = schema.newValidator();
    validator.setErrorHandler(new ErrorHandler());
    validator.validate(new StreamSource(xml));
  } 
 
} 
 
/** 
 * XML handler that throws exception on error and warning, does nothing otherwise. 
 */ 
class ErrorHandler extends DefaultHandler {
 
  @Override 
  public void warning (SAXParseException e) throws SAXException {
    System.err.println(e.getMessage()
        + " Problem found at line " + e.getLineNumber() 
        + ", column " + e.getColumnNumber() + ".");