0

Javaで検証するために次のコードを記述しましたが、常にtrueを返します。XMLを変更してXSDとの互換性をなくしても、trueを返します。ご覧ください。

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

1 に答える 1

2

ErrorHandlerインターフェイスの実装で、次のことを試してください。

それ以外の

exceptions.add(exception);

以下をせよ

throw exception;

実装が検証例外を消費している可能性があります。exceptionsまた、その内容に基づいて確認して返すこともできます。後で使用することのないリストを埋めているのはなぜですか?

于 2012-11-09T09:26:11.453 に答える