如何在 saxon api (.net) 中启用模式验证

How to enable schema validation in saxon api (.net)

我已经为 dotnet 下载了最新的 9ee 版本的 saxon api。 我有一个简单的程序可以从 xslt 转换 xml。 它适用于简单的 xslts,但我似乎看不到如何启用模式验证(xslt 文档)。

这是我的 C#(感谢

    public static string TransformXml(string xmlData, string xslData)
    {
        var xsltProcessor = new Processor(true);

        var documentBuilder = xsltProcessor.NewDocumentBuilder();
        documentBuilder.BaseUri = new Uri("file://");
        var xdmNode = documentBuilder.Build(new StringReader(xmlData));

        var xsltCompiler = xsltProcessor.NewXsltCompiler();
        var xsltExecutable = xsltCompiler.Compile(new StringReader(xslData));
        var xsltTransformer = xsltExecutable.Load();
        xsltTransformer.InitialContextNode = xdmNode;

        var results = new XdmDestination();

        xsltTransformer.Run(results);
        return results.XdmNode.OuterXml;
    }

这是我的 xslt(主要取自“掌握 xslt”Doug Tidwell)

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="2.0">
    
    <xsl:output method="text" />
    
<xsl:import-schema schema-location="file:///C:/Users/m_r_n/source/repos/SaxonEEExample/ValidateXslt/po1.xsd" />

    <xsl:template match="schema-element(PurchaseOrder)">
      <xsl:for-each select="item">
            <xsl:value-of select="@id" />: <xsl:value-of select="title" />
            <xsl:text>&#xa;</xsl:text>
        </xsl:for-each>
    </xsl:template>
    
    <xsl:template match="*">
        <xsl:message terminate="yes">Source document is not a purchase order
        </xsl:message>
    </xsl:template>
    
</xsl:stylesheet>

当我 运行 它时,我得到 “源文件不是采购订单”......

如果我删除“模式元素”功能,那么我会得到所需的

100: Water for Elephants
101: Glass Castle: A Memoir
200: 5 Amp Electric plug

我的直觉是 xslt 是正确的,但我在 API 上遗漏了一些设置(为了公平起见,撒克逊示例,不包括此类内容)


编辑

实际上,老实说,我希望能够做两件事,1 根据输入模式(导入模式)验证 xslt 并使用这些构造针对 xslt 执行 XSLT,作为 2 个单独的操作。


编辑

所以在评论中采纳 Michael Kay 的反馈。

我已经回到撒克逊示例,并借用了验证器示例。

我没有验证实例文档,而是尝试验证 XSLT 本身。

        var samplesDir = new Uri(AppDomain.CurrentDomain.BaseDirectory);

        Processor processor = new Processor(true);
        processor.SetProperty("http://saxon.sf.net/feature/timing", "true");
        processor.SetProperty("http://saxon.sf.net/feature/validation-warnings", "false"); //Set to true to suppress the exception
        SchemaManager manager = processor.SchemaManager;
        manager.XsdVersion = "1.1";
        manager.ErrorList = new List<StaticError>();
        Uri schemaUri = new Uri(samplesDir, "po1.xsd");

        try
        {
            manager.Compile(schemaUri);
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            Console.WriteLine("Schema compilation failed with " + manager.ErrorList.Count + " errors");
            foreach (StaticError error in manager.ErrorList)
            {
                Console.WriteLine("At line " + error.LineNumber + ": " + error.Message);
            }
            return;
        }


        // Use this to validate an instance document

        SchemaValidator validator = manager.NewSchemaValidator();

        XmlReaderSettings settings = new XmlReaderSettings();
        settings.DtdProcessing = DtdProcessing.Ignore;
        String inputFileName = new Uri(samplesDir, "po.xsl").ToString();
        XmlReader xmlReader = XmlReader.Create(inputFileName, settings);
        validator.SetSource(xmlReader);
        Console.WriteLine("Validating input file " + inputFileName);
        validator.ErrorList = new List<ValidationFailure>();
        XdmDestination psvi = new XdmDestination();
        validator.SetDestination(psvi);

        try
        {
            validator.Run();
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            Console.WriteLine("Instance validation failed with " + validator.ErrorList.Count + " errors");
            foreach (ValidationFailure error in validator.ErrorList)
            {
                Console.WriteLine("At line " + error.GetLineNumber() + ": " + error.GetMessage());
            }
            return;
        }

控制台上的结果是

Loading schema document file:///C:/Users/m_r_n/source/repos/SaxonEEExample/ValidateXslt/bin/Debug/po1.xsd
Using parser org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser
Found registry key at HKEY_LOCAL_MACHINE\Software\Saxonica\SaxonEE-N\Settings
Software installation path: c:\Program Files\Saxon\SaxonEE9.9N
Finished loading schema document file:///C:/Users/m_r_n/source/repos/SaxonEEExample/ValidateXslt/bin/Debug/po1.xsd
Validating input file file:///C:/Users/m_r_n/source/repos/SaxonEEExample/ValidateXslt/bin/Debug/po.xsl
One validation error was reported: Cannot validate <Q{.../Transform}stylesheet>: no element declaration available
Instance validation failed with 1 errors
At line 2: Cannot validate <Q{.../Transform}stylesheet>: no element declaration available

有两种方法。

您可以使用 xsl:import-schema 来加载架构,但是只有 XSLT 处理器知道架构,因此需要在 XSLT 的控制下构建和验证输入文档。如果您在 XsltTransformer 上设置 SchemaValidationMode,并将输入作为未解析的 Stream 提供给 XsltTransformer,那么它将使用架构验证进行解析。

另一种方法是像您一样使用 DocumentBuilder,并确保它进行验证。为此,您需要使用 SchemaManager.Compile 加载架构,然后从该架构创建一个 SchemaValidator,并将其提供给 DocumentBuilder.

公平地说,Michael Kay 回答了这个问题,我只是为了完整性而提出这个问题,这几乎是最小的例子。

如果 XSLT 引用了架构中未引用的无效节点(我使用了“PurchaseOrder1”),这将在“编译”期间失败(有例外)。

        var samplesDir = new Uri(AppDomain.CurrentDomain.BaseDirectory);
        // Create a Processor instance.
        Processor processor = new Processor(true);

        // Create a transformer for the stylesheet.
        //Xslt30Transformer transformer = processor.NewXsltCompiler().Compile(new Uri(samplesDir, "poNoValidation.xsl")).Load30();
        Xslt30Transformer transformer = processor.NewXsltCompiler().Compile(new Uri(samplesDir, "po.xsl")).Load30();

        // Create a serializer, with output to the standard output stream
        Serializer serializer = processor.NewSerializer();
        serializer.SetOutputWriter(Console.Out);

        // Transform the source XML and serialize the result document
        transformer.SchemaValidationMode = SchemaValidationMode.Strict;
        transformer.ApplyTemplates(File.OpenRead("po.xml"), serializer);