首页 > 解决方案 > 如何使用 Saxon API 从模式感知 xslt 获取警告

问题描述

我有一些编译然后执行 XSLT 的 c# 原型代码。

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


        var compiler = processor.NewXsltCompiler();
        try
        {
            // Create a transformer for the stylesheet.
            Xslt30Transformer transformer = compiler.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);
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            Console.WriteLine("Schema compilation failed with " + compiler.ErrorList.Count + " errors");
            foreach (StaticError error in compiler.ErrorList)
            {
                Console.WriteLine("At line " + error.LineNumber + ": " + error.Message);
            }
        }

和一个 XSLT 文件

<?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>

如果我将比赛更改为

<xsl:template match="schema-element(PurchaseOrder1)">

那么这将正确报告错误

  At line 8: There is no declaration for element <PurchaseOrder1> in an imported schema

杰出的。

如果我将其改回并将 for-each 行修改为

  <xsl:for-each select="item1">

然后是氧气编辑器(使用 Saxon EE),正确报告此行的警告

The complex type of element PurchaseOrder does not allow a child element named item1

但是我的 C# 代码会很高兴地编译并执行它(输出一个空字符串)。

如何让撒克逊编译器报告警告?Oxygen 做了什么我的代码没有做的事情?

标签: saxon

解决方案


Saxon 可能正在向控制台输出警告,而您看不到控制台上的内容。

尝试通过ErrorList设置.ErrorReporterXsltCompiler


推荐阅读