【问题标题】:XML transformation using XSLT version 2使用 XSLT 版本 2 进行 XML 转换
【发布时间】:2016-07-14 14:06:13
【问题描述】:

我正在尝试使用 XSLT 2.0 版转换 XML,但出现以下异常:

找不到与命名空间“http://www.w3.org/2001/XMLSchema”关联的脚本或扩展对象。

后来我知道微软不支持 XSLT 2.0 版。 请参阅link。它建议使用一些第三方工具。但是这些工具有一些相关的许可费用。有没有类似的免费软件可用?

[编辑]

我尝试使用 SaxonHe

  public static void Func( string xsltFile,string inputFile, string outputFile)
    {

        var  xslt = new FileInfo(xsltFile);
        var input = new FileInfo(inputFile);
        var output = new FileInfo(outputFile);
        // Compile stylesheet
        var processor = new Processor(false);
        var compiler = processor.NewXsltCompiler();
        var executable = compiler.Compile(new Uri(xslt.FullName));


        // Do transformation to a destination
        var destination = new DomDestination();
        using (var inputStream = input.OpenRead())
        {
            var transformer = executable.Load();
            transformer.SetInputStream(inputStream, new Uri(input.DirectoryName));
            transformer.Run(destination);
        }

        destination.XmlDocument.Save(output.FullName);
    }

在最后一条语句上给出空引用异常是行不通的。实际上destination.XmlDocument 正在获取空值。

【问题讨论】:

  • Saxon 9 HE 是开源的,nuget.org/packages/Saxon-HE
  • 感谢马丁的建议。我尝试使用 Saxon 9 He,但它不适合我。我已经编辑了带有详细信息的问题。
  • 我可以尝试帮助将 Saxon 与 C# 结合使用,但我认为您应该首先说明目标是什么,您想在磁盘上创建结果文档吗?您的代码尝试创建 XmlDocument 只是为了将其保存到看起来的文件中,所以我想知道这是否是您发现将结果写入文件的唯一方法,或者您是否希望将结果保存在 XmlDocument也可以作为文件。

标签: c# c#-4.0 xslt-2.0


【解决方案1】:

我认为如果您只想将转换结果创建为文件,那么您不需要 DomDestination,您可以使用 Serializer,如

    static void Main(string[] args)
    {
        TestTransform("XSLTFile1.xslt", "XMLFile1.xml", "Result1.xml");
    }

    public static void TestTransform(string xsltFile, string inputFile, string outputFile)
    {

        var xslt = new FileInfo(xsltFile);
        var input = new FileInfo(inputFile);
        var output = new FileInfo(outputFile);

        // Compile stylesheet
        var processor = new Processor(false);
        var compiler = processor.NewXsltCompiler();
        var executable = compiler.Compile(new Uri(xslt.FullName));


        using (var inputStream = input.OpenRead())
        {
            var transformer = executable.Load();
            transformer.SetInputStream(inputStream, new Uri(input.DirectoryName));

            var serializer = new Serializer();

            using (var resultStream = output.OpenWrite())
            {
                serializer.SetOutputStream(resultStream);
                transformer.Run(serializer);
            }
        }


    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多