我在哪里可以找到ISO Schematron验证器的Java实现?

时间:2012-04-12 15:00:04

标签: java schematron

ISO Schematron标准已经推出两年了,但我仍然无法使用ISO Schematron XSLT文件找到Java实现(而不是旧版Schematron的文件,例如:{{3} })。

有没有人知道可以从Java方法轻松调用的生产就绪的ISO模式验证器?

4 个答案:

答案 0 :(得分:9)

此外,您可以使用ph-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 ();
}

答案 1 :(得分:6)

Probatron4j可以针对ISO Schematron进行验证。该网站提供了一个单独的,独立的JAR,旨在从命令行运行,但如果你有its source code,很容易从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文件中运行的,但它不需要很长时间。

答案 2 :(得分:0)

您可以查看SchematronAssert(披露:我的代码)。它主要用于单元测试,但您也可以将它用于普通代码。它是使用XSLT实现的。

单元测试示例:

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() ...

答案 3 :(得分:-1)

jing库对我有用。