user900721
user900721

Reputation: 1437

Error while XML validation against the XSD

I have written following code for validation in java, but it always return true. Even if I modify XML and make not compatible to XSD, still it return true. Please take a look.

public static boolean isValidXML(String filePath,String xsdFile){
    boolean bValue = true;
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    try {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder parser = documentBuilderFactory.newDocumentBuilder();
        Document document = parser.parse(new File(filePath));

        Schema schema = schemaFactory.newSchema(new File(xsdFile));
        Validator validator = schema.newValidator();

        final List<SAXParseException> exceptions = new LinkedList<SAXParseException>();
        validator.setErrorHandler(new ErrorHandler()
        {
          public void warning(SAXParseException exception) throws SAXException
          {
            exceptions.add(exception);
          }

          public void fatalError(SAXParseException exception) throws SAXException
          {
            exceptions.add(exception);
          }

          public void error(SAXParseException exception) throws SAXException
          {
            exceptions.add(exception);
          }
        });
        validator.validate(new DOMSource(document));
    } catch (SAXException e) {
        bValue = false;
        logger.error("Error while Validating the XML."+e);
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return bValue;
}

Upvotes: 0

Views: 246

Answers (1)

predi
predi

Reputation: 5928

In your ErrorHandler interface implementation, try the following:

instead of

exceptions.add(exception);

do the following

throw exception;

Your implementation might be consuming validation exceptions. You could also check exceptions and return based on it's contents. Why are you filling a list which you never use later?

Upvotes: 2

Related Questions