0

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;
}

1 Answer 1

2

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?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.