After finding the best approach to validating my XML in XSD, I came across java.xml.validator.
I started by using the sample code from the API and adding my own ErrorHandler
// parse an XML document into a DOM tree DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = parser.parse(new File("instance.xml")); // create a SchemaFactory capable of understanding WXS schemas SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); // load a WXS schema, represented by a Schema instance Source schemaFile = new StreamSource(new File("mySchema.xsd")); Schema schema = factory.newSchema(schemaFile); // create a Validator instance, which can be used to validate an instance document Validator validator = schema.newValidator(); // Add a custom ErrorHandler validator.setErrorHandler(new XsdValidationErrorHandler()); // validate the DOM tree try { validator.validate(new DOMSource(document)); } catch (SAXException e) { // instance document is invalid! } ... private class XsdValidationErrorHandler implements ErrorHandler { @Override public void warning(SAXParseException exception) throws SAXException { throw new SAXException(exception.getMessage()); } @Override public void error(SAXParseException exception) throws SAXException { throw new SAXException(exception.getMessage()); } @Override public void fatalError(SAXParseException exception) throws SAXException { throw new SAXException(exception.getMessage()); } }
This works fine, however, the message passed to my XsdValidationErrorHandler does not give me any indication of exactly where the XML-violating document is located:
"org.xml.sax.SAXParseException: cvc-complex-type.2.4.a: Invalid content was found starting with element 'X'. One of '{Y}' is expected."
Is there a way to override or mount another Validator section so that I can define my own error messages sent to ErrorHandler without having to rewrite all the code?
Should I use a different library?
java xml validation xsd
Levity
source share