Thursday, April 19, 2012

How to validate an XML against XSD schema

I found this to be useful to share with you all. Because XML validation against a defined schema is very essential.

I will be mainly using Apache Xerces library to implement this functionality.

You will need these to be as imports to the following code block.
import org.apache.xerces.parsers.SAXParser;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.helpers.DefaultHandler;
This will be the code block.
  SAXParser parser = new SAXParser();
                
  parser.setFeature("http://xml.org/sax/features/validation", true);
  parser.setFeature("http://apache.org/xml/features/validation/schema",true);

  //Set the validation/schema feature to true to report validation errors against a schema.
  parser.setFeature("http://apache.org/xml/features/validation/schema-full-  checking", true);

  parser.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", "FileURLToTheSchema");

  Validator handler = new Validator();
  parser.setErrorHandler(handler);

  parser.parse(URLToTheXMLFile);

  FileURLToTheSchema,URLToTheXMLFile are URLs given as i.e file:///home/etc/.. 

You can use your own schema and a sample corresponding XML file and test this. This will throw meaningful Exceptions when parsing fails.

So following will be the Validator class which is mentioned above. This will allows us to register it as an ErrorHandler with the parser.

import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;

public class Validator extends DefaultHandler {

    public boolean validationError = false;
    public SAXParseException saxParseException = null;

    public void error(SAXParseException exception)
            throws SAXException {
        validationError = true;
        saxParseException = exception;
    }

    public void fatalError(SAXParseException exception)
            throws SAXException {
        validationError = true;
        saxParseException = exception;
    }

    public void warning(SAXParseException exception)
            throws SAXException {
    }
}
References : http://onjava.com/onjava/2004/09/15/schema-validation.html