Load xml and xslt from embedded resource in Saxon 9.4he

不问归期 提交于 2019-11-29 10:56:25

I think you can load from a stream with Saxon but you need to set a base URI first that would allow to load any references resources (like a DTD in an XML document or like included or imported stylesheet modules). If you are sure you don't have that then simply try e.g.

DocumentBuilder db = processor.NewDocumentBuilder();
db.BaseUri = new Uri("file:///C:/");

XdmNode input = db.Build(xsltStream);

Obviously if you need to resolve relative URIs in the XSLT that are also to be loaded as embedded resource more work is needed: you need to set up the XmlResolver to a class that supports loading the resource from an embedded resource, together with a scheme of URIs in the XSLT to indicate to the resolver that you need to load from a resource. I don't think the .NET framework provides such a kind of XmlResolver and the Uri class does not support a custom schema for that either.

Recently,I encountered this problem. And this is my solution.

private void test() {
        Stream xsltStream = GetEmbeddedResource("TestSaxon.Resources.test.xsl");

        Processor processor = new Processor();

        DocumentBuilder db = processor.NewDocumentBuilder();
        XmlDocument xmlDocument = new XmlDocument();
        xmlDocument.Load(xsltStream);

        XdmNode xdmNode = db.Build(xmlDocument);

        XsltTransformer transformer = processor.NewXsltCompiler().Compile(xdmNode).Load();
        var path = AppDomain.CurrentDomain.BaseDirectory;
        var input = new FileInfo(path + @"\input.xml");
        var output = new FileInfo(path + @"\result.xml");
        var destination = new DomDestination();
        using (var inputStream = input.OpenRead())
        {
            transformer.SetInputStream(inputStream, new Uri(input.DirectoryName));
            transformer.Run(destination);
        }
        destination.XmlDocument.Save(output.FullName);
    }

    protected static Stream GetEmbeddedResource(string path)
    {
        Assembly asm = Assembly.GetExecutingAssembly();
        Stream stream = asm.GetManifestResourceStream(path);
        return stream;
    }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!