[英]Error while XML validation against the XSD
I have written following code for validation in java, but it always return true. 我在java中编写了以下代码进行验证,但它总是返回true。 Even if I modify XML and make not compatible to XSD, still it return true.
即使我修改XML并使其与XSD不兼容,它仍然返回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;
}
In your ErrorHandler
interface implementation, try the following: 在
ErrorHandler
接口实现中,尝试以下操作:
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. 您还可以检查
exceptions
并根据其内容返回。 Why are you filling a list which you never use later? 为什么要填写以后从未使用的列表?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.