0
votes

I am validating an xml instance against multiple XSD schemas. If validation fails, I want to determine which schema the xml instance failed against. The SAXParseException does not contain enough information to determine this.

SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
Source[] sources = getXsdSources();
Schema schema = factory.newSchema(sources);
Validator validator = schema.newValidator();

try {
  validator.validate(input);
} catch (SAXParseException e) {
  // Error handling.
}
3

3 Answers

0
votes

@Joe, The following link might help you. You can find same question asked in Stackoverflow earlier. Validate an XML File Against Multiple Schema Definitions

0
votes

you will need to validate each schema individually instead of loading them all into 'schema'. then its a simple matter of iterating over the list of 'sources' setting 'validator' to each one, so you can keep track of which was loaded at the time of failure.

this is not tested, but should be about right:

SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    Source[] sources = getXsdSources();
    foreach( Source s : sources){
    Schema schema = factory.newSchema(s);
    Validator validator = schema.newValidator();
    try {
      validator.validate(input);
    } catch (SAXParseException e) {
      // Error handling.
      System.out.println("failed on " + s.getSystemID)
    }
}
0
votes

Xerces J provides access to all (or possibly only almost all?) of the post-schema validation infoset (PSVI), which includes information about the type against which an element or attribute was validated and the nature of any invalidity. See http://xerces.apache.org/xerces2-j/faq-xs.html#faq-8 for more info.

If the validator you're using is Xerces J, the information you need is available (perhaps in the exception wrapped by the SAXParseException you are handling?); if you're using another validator, you can either explore its API a bit more or you can use Xerces J.