首页 > 解决方案 > 使用 python 和 xslt 2.0 进行 schematron 验证

问题描述

我有一个使用 XSLT 2.0 的 Schematron 文档,我正在寻找一种在 python 中使用 Schematron 规则验证一系列 xml 的方法。

我试过lxml,但它不支持XSLT 2.0,我也试过使用saxonc api,当我尝试初始化它时它似乎只是崩溃了。

有没有人成功地在 python 中处理 XSLT 2.0 以进行 Schematron 验证?

标签: python-3.xxslt-2.0schematron

解决方案


schxslt-1.5.2-xslt-only.zip我从https://github.com/schxslt/schxslt/releases/tag/v1.5.2下载了最新的 Schxslt 版本 1.5.2 ,并在 Windows 上使用 Python 3.7 和 Saxon-C HE 1.2.1 运行以下示例 Python 程序:

import saxonc

with saxonc.PySaxonProcessor(license=False) as proc:
    print("Test Saxon/C on Python")
    print(proc.version)

    xslt30_processor = proc.new_xslt30_processor()

    xslt30_processor.set_cwd(".")

    xslt30_processor.transform_to_file(source_file="price-xslt2.sch", stylesheet_file="../../../schxslt-1.5.2/2.0/pipeline-for-svrl.xsl", output_file="price-compiled-saxon-c.xsl")

    xslt30_processor.transform_to_file(source_file="books.xml", stylesheet_file="price-compiled-saxon-c.xsl", output_file="saxon-c-report-books.xml")

这运行良好,第一次transform_to_file调用会生成一个 XSLT 文件price-compiled-saxon-c.xsl,第二次transform_to_file调用将应用于输入样本并生成一个验证报告为saxon-c-report-books.xml.

如果您想避免中间文件,那么以下方法也可以:

import saxonc

with saxonc.PySaxonProcessor(license=False) as proc:
    print("Test Saxon/C on Python")
    print(proc.version)

    xslt30_processor = proc.new_xslt30_processor()

    xslt30_processor.set_cwd(".")

    compiled_schematron = xslt30_processor.transform_to_value(source_file="price-xslt2.sch", stylesheet_file="../../../schxslt-1.5.2/2.0/pipeline-for-svrl.xsl")
    
    stylesheet_node = compiled_schematron.item_at(0).get_node_value()

    xslt30_processor.compile_stylesheet(stylesheet_node = stylesheet_node)

    xslt30_processor.transform_to_file(source_file="books.xml", output_file="saxon-c-report-3-books.xml")

唯一未知的因素是我安装的 Saxon-C 1.2.1,我不知道它是否与您可以从 Saxonica 下载的最新版本相同,因为它已经存在一年了,并且在https://saxonica 上有各种错误报告。 plan.io/projects/saxon-c导致了一些我可能已经应用的修复;不幸的是,到目前为止,Saxonica 从未发布包含所有修复程序的新维护版本。

如果您在从 Python 运行 Saxon-C 时遇到问题,我想最好在他们的支持论坛上打开一个问题或问题,其中包含所有最少但完整的细节来重现它,我相信他们会帮助您告诉您如何起床和跑步。


推荐阅读