Thursday, May 17, 2012

Validate XML against XML Schema using Java

Taking up the Employees.xsd schema and Employees.xml again for this illustration as well.
We want to validate the xml instance against the schema and want to achieve this through Java code. Not challenging, eh? Ageed, however thought I'd pen it here for future references.

Here's the code that achieves it -
public class SchemaValidation {

  private static void validateXML(File sourceFile, File schemaFile) throws IOException,SAXException {

    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    Schema schema = schemaFactory.newSchema(schemaFile);

    Validator validator = schema.newValidator();
    try {
      validator.validate(new StreamSource(sourceFile));
      System.out.println("is valid");
    } catch (SAXException e) {
      System.out.println("not valid because " + e.getLocalizedMessage());
    }
  }

  public static void main(String args[]) throws ParserConfigurationException, IOException,
      SAXException {

    File file = new File("Employees.xml");
    File schemaFile = new File("Employees.xsd");
    SchemaValidation.validateXML(file, schemaFile);
  }
}
So when I try validating the XML below against the Employees xsd schema -

<?xml version="1.0" encoding="UTF-8"?>
<tns:Employees xmlns:tns="http://www.example.org/Employees">
    <tns:Employee>
        <tns:Name>tns:Name</tns:Name>
        <tns:ID>tns:ID</tns:ID>
        <tns:Designation>tns:Designation</tns:Designation>
        <tns:Dept1>tns:Dept</tns:Dept1>
    </tns:Employee>
</tns:Employees>

I get the output -
not valid because cvc-complex-type.2.4.a: Invalid content was found starting with element 'tns:Dept1'. One of '{"http://www.example.org/Employees":Dept}' is expected.

So you see, the XML Parser pin points the exact error location along with the resolution. So for the above case it expects a <Dept> tag whereas what I pass is <Dept1>. Hence, the error.
   


No comments:

Post a Comment