public static boolean IsValid(InputStream xml, InputStream xsd)
{
try
{
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(new StreamSource(xsd));
Validator validator = schema.newValidator();
validator.validate(new StreamSource(xml));
return true;
}
catch (Exception ex)
{
return false;
}
}
正如您所看到的,异常用于控制流,我想更改它,因为这不是一个好的实践,因为异常应该仅用于异常情况。 (也许有人会说,如果 xml 无效,那么在某些情况下这确实是一种异常(exception)情况......)
validate
方法有另一个签名 validate(Source source, Result result)
,但是看看 Result
接口(interface)并没有真正的签名。帮助我。
/**
* Set the system identifier for this Result.
*
* <p>If the Result is not to be written to a file, the system identifier is optional.
* The application may still want to provide one, however, for use in error messages
* and warnings, or to resolve relative output identifiers.</p>
*
* @param systemId The system identifier as a URI string.
*/
public void setSystemId(String systemId);
/**
* Get the system identifier that was set with setSystemId.
*
* @return The system identifier that was set with setSystemId,
* or null if setSystemId was not called.
*/
public String getSystemId();
那么如何根据架构验证 XML?这不需要是我的方法!它是否打算按照我的方式使用validate
?
最佳答案
我认为你应该实现 ErrorHandler
,例如通过扩展 DefaultHandler
,然后通过调用 Validator#setErrorHandler()
将其注册到您的Validator
.
您的 ErrorHandler 可以记录所有验证错误(以及警告,如果您对它们感兴趣)。不要忘记实现/覆盖 fatalError(...)
方法,以便当文档无法解析时(例如,由于文档格式不正确),您会收到通知.
只要您的 ErrorHandler
不抛出任何异常,对 validate()
的调用也不会抛出任何异常。它的 Javadoc 声明它将抛出 SAXException
if the
ErrorHandler
throws aSAXException
or if a fatal error is found and theErrorHandler
returns normally.
因此应该可以验证文档而不依赖控制流的异常处理。只要您询问 ErrorHandler
在验证文档后是否发现任何错误。不幸的是,如果您的文档格式不正确,您仍然必须捕获 SAXParseException
。
关于java - 如何在不使用控制流异常的情况下根据模式验证 XML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17785709/