2012-11-09 70 views
0

我已经写了下面的代码在Java验证,但它总是返回true。即使我修改XML并且与XSD不兼容,它仍然会返回true。请看一下。错误,而XSD的XML验证

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

回答

2

在你ErrorHandler接口的实现,请尝试以下几种:

代替

exceptions.add(exception); 

做以下

throw exception; 

您的实现可能会耗费验证异常。您也可以检查exceptions并根据其内容返回。你为什么填写你以后从不使用的清单?