XSLT transformation in memory using C#

2020-03-26 06:00发布

Good afternoon all,

I dont know why this is proving so difficult but I must be having one of those days!

I am trying to perform and XslCompiledTransform on an in memory XmlDocument (I have retrieved the XML from a webservice and saved to a database) object. I have the following code so far:

        string xslFile = "C:\\MOJLogViewer\\GetClaimTransformed.xslt";

        XslCompiledTransform processor = new XslCompiledTransform();
        processor.Load(xslFile);

        MemoryStream ms = new MemoryStream();
        processor.Transform(xdoc.CreateNavigator(), null, ms);

        ms.Seek(0, SeekOrigin.Begin);

        StreamReader reader = new StreamReader(ms);

        XmlDocument transformedDoc = new XmlDocument();
        transformedDoc.Load(reader.ReadToEnd());


        string output = reader.ReadToEnd();
        ms.Close();

When I try to run this code I get the "illegal characters in path" exception. The path does not contain any of the illegal characters so I am absolutely stumped!

I hope you can help.

Thanks

1条回答
姐就是有狂的资本
2楼-- · 2020-03-26 06:18
transformedDoc.Load(reader.ReadToEnd());

Load reads from a path; you probably want transformedDoc.LoadXml(...). But in all honesty, you could just write the whole thing to a StringWriter - more direct:

string output;
using(var writer = new StringWriter())
{
    processor.Transform(xdoc.CreateNavigator(), null, writer);
    output = writer.ToString();
}

Plus it will work for non-xml outputs (xslt is not obliged to output xml).

查看更多
登录 后发表回答