Posts Tagged ‘schema validation’

Validating a xml against an xml schema using java

November 19, 2008

WSO2 maintaines the eclipse axis2 plugins for eclipse. I working on plugins for wso2, sometime back wanted to validate a user given services.xml file with the relevant schema. Eventhough it took me a while to findout how to do it, it is actually pretty simple to do. But its best to write it down somewhere so someone (which includes me) can next time find it out easily and understand it without problems. Following is the code snippet on how to do it by java.


import java.io.File;

import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
....
....
public boolean isXMLValid(String xmlPath, String schemaPath){
SchemaFactory factory = SchemaFactory.newInstance(
                     "http://www.w3.org/2001/XMLSchema");
try {
Schema schema = factory.newSchema(new File(schemaPath));
Validator validator = schema.newValidator();
Source source = new StreamSource(new File(xmlPath));
validator.validate(source);
return true;
} catch (Exception ex) {
return false;
}
}

So its pretty easy. If you know the paths of the two files (i.e. the xml file which you want to validate and the xsd file which you want to validate against), using the above function you can do it. If the function true returns that means the xml is in accordance with the schema. Take notice that this validation is case sensitive. That means the uppercase and lowercase are considered different eventhough they are the same words. The schema will take in to the case sensitivity in to consideration when validating.

Some times what you have may be the url of the xml or schema. In which case just use

new URL(<url_address>)

instead of

new File(file_path)

It is as simple as that. If the validation fails there will always be an exception in which case we return false. But if you want to know what the error was in the xml file simply analyse the exception that was thrown. It consists of details which caused the validator to decide it is not according to the schema.