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 无效,在某些情况下这确实是一种例外情况......)
该validate
方法有另一个签名validate(Source source, Result result)
,但看看Result
界面并没有真正帮助我。
/**
* 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();
那么如何根据 Schema 验证 XML?它不需要是我的方法!是否打算使用validate
我的方式?