Where can I find a Java implementation of an ISO Schematron validator?

本小妞迷上赌 提交于 2019-11-30 07:49:36

Additionally you may use ph-schematron which provides both support for conversion to XSLT as well as a native plain Java validation, which is quicker than the XSLT version in nearly all cases. See https://github.com/phax/ph-schematron/ for the details as well as a quick intro. Example code to check if an XML file matches a Schematron file:

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 can validate against ISO Schematron. The website provides a single, self-contained JAR that's designed to be run from the command line, but it's easy to call Probatron from a Java method if you have its source code. Here's a simplified version of how I did it:

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;
}

You'll need to make a few minor modifications to let Probatron know it's not being run from within a JAR file, but it doesn't take long.

You can check out SchematronAssert (disclosure: my code). It is meant primarily for unit testing, but you may use it for normal code too. It is implemented using XSLT.

Unit testing example:

ValidationOutput result = in(booksDocument)
    .forEvery("book")
    .check("author")
    .validate();
assertThat(result).hasNoErrors();

Standalone validation example:

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);

Work with an object representation of SVRL:

ValidationOutput output = validator.validate(xmlSource, schemaSource);
// look at the output
output.getFailures() ... 
output.getReports() ...
Baran Küçükgüzel

The jing library works for me.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!