两年前,ISO Schematron标准已经发布,但我仍然找不到使用ISO Schematron XSLT文件的Java实现(而不是来自较旧版本Schematron的文件,例如这里:http://uploading.com/files/c9c9cb87/SchematronXpath.jar/)。
有没有人知道一个能够轻松从Java方法调用的生产就绪的ISO模式验证器?
有没有人知道一个能够轻松从Java方法调用的生产就绪的ISO模式验证器?
ph-schematron
,它不仅提供将Schematron转换为XSLT的支持,还提供本地Java验证,几乎在所有情况下都比XSLT版本快。
有关详细信息以及快速介绍,请参见https://github.com/phax/ph-schematron/。
用于检查XML文件是否与Schematron文件匹配的示例代码:public static boolean validateXMLViaPureSchematron (File aSchematronFile, File aXMLFile) throws Exception {
final ISchematronResource aResPure = SchematronResourcePure.fromFile (aSchematronFile);
if (!aResPure.isValidSchematron ())
throw new IllegalArgumentException ("Invalid Schematron!");
return aResPure.getSchematronValidity(new StreamSource(aXMLFile)).isValid ();
}
Probatron4j 可以校验 ISO Schematron。该网站提供了一个单独的、自包含的 JAR 文件,可在命令行中运行,但如果您有其源代码,那么很容易从 Java 方法中调用 Probatron。以下是我简化后的做法:
public boolean validateSchematron(InputStream xmlDoc, File schematronSchema) {
// Session = org.probatron.Session; think of it as the Main class
Session theSession = new Session();
theSession.setSchemaSysId(schematronSchema.getName());
theSession.setFsContextDir(schematronSchema.getAbsolutePath());
// ValidationReport = org.probatron.ValidationReport; the output class
ValidationReport validationReport = null;
try
{
validationReport = theSession.doValidation(xmlDoc);
}
catch(Exception e) { /* ignoring to keep this answer short */ }
if (validationReport == null ||
!validationReport.documentPassedValidation()) {
return false;
}
return true;
}
您需要进行一些小修改来告诉Probatron它不是在JAR文件中运行,但这并不需要很长时间。
ValidationOutput result = in(booksDocument)
.forEvery("book")
.check("author")
.validate();
assertThat(result).hasNoErrors();
独立验证示例:
StreamSource schemaSource = new StreamSource(... your schematron schema ...);
StreamSource xmlSource = new StreamSource(... your xml document ... );
StreamResult output = ... here your SVRL will be saved ...
// validation
validator.validate(xmlSource, schemaSource, output);
使用SVRL的对象表示进行工作:
ValidationOutput output = validator.validate(xmlSource, schemaSource);
// look at the output
output.getFailures() ...
output.getReports() ...