Question

I have some Java code that validates XML against an XSD. I am using a modified version of the Error Handler found here: http://www.ibm.com/developerworks/xml/library/x-javaxmlvalidapi.html to catch and log ALL exceptions while validating.

The errors are very terse, they look something like this:

http://www.w3.org/TR/xml-schema-1#cvc-complex-type.2.4.a?s:cID&{"http://www.myschema.com/schema":txn}

Other messages such as

http://www.w3.org/TR/xml-schema-1#cvc-complex-type.2.4.a?s:attributes&{"http://www.myschema.com/schema":sequence}

are even more cryptic.

Is there an easy way to get a clear and intelligible message out of SAX explaining what went wrong here? I think in the first error it was expecting txn and instead found the element cID. BUT... I don't know all the possible errors that might be generated by SAX so I'd rather not try to manually create a translation table.

The eventual users of this output are mostly non-technical so I need to be able generate simple and clear messages such as "element txn was out of sequence".

If it helps, here's the code (more or less) that's used for validation:

Source schema1 = new StreamSource(new File("resources/schema1.xsd"));
Source schema2 = new StreamSource(new File("resources/schema2.xsd"));
Source[] sources = {schema1,schema2};
validator = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(sources).newValidator();
ErrorHandler lenient = new ForgivingErrorHandler();
validator.setErrorHandler(lenient);

Elsewhere...

StreamSource xmlSource = new StreamSource(new StringReader(XMLData) );
try
{
    validator.validate(xmlSource);
}
catch (SAXException e)
{
    logger.error("XML Validation Error: ",e);
}
Was it helpful?

Solution

Well, it seems I had to add xsi:schemaLocation="http://www.mycompany.com/schema resources/schema1.xsd " to the XML document, because s:http://www.mycompany.com/schema is the default namespace: xmlns="s:http://www.mycompany.com/schema". Of course, I don't have access to modify the tool that generates the XML, so the following ugly hack was necessary:

xmlDataStr = xmlDataStr.replace("<rootNode ", "<rootNode xsi:schemaLocation=\"http://www.mycompany.com/schema resources/schema1.xsd \" ");

...of course now I'm getting double validation errors! A clear and intelligible one such as:

cvc-complex-type.2.4.a: Invalid content was found starting with element 's:cID'. One of '{"http://www.mycompany.ca/schema":tdr}' is expected.

Immediately followed by:

http://www.w3.org/TR/xml-schema-1#cvc-complex-type.2.4.a?s:cID&{"http://www.mycompany.com/schema":tdr}

The double-error is annoying but at least the first one is usable...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top