How to transform XML as a string w/o using files i

2019-01-11 10:26发布

Let's say I have two strings:

  • one is XML data
  • and the other is XSL data.

The xml and xsl data are stored in database columns, if you must know.

How can I transform the XML in C# w/o saving the xml and xsl as files first? I would like the output to be a string, too (HTML from the transformation).

It seems C# prefers to transform via files. I couldn't find a string-input overload for Load() in XslCompiledTransform. So, that's why I'm asking.

标签: c# xml xslt
7条回答
孤傲高冷的网名
2楼-- · 2019-01-11 11:07

It took me a long time (literally years) to work out how concise code using Stream and/or TextWriter can be if you use the proper idioms.

Assuming transform and input are strings:

StringWriter sw = new StringWriter();
using (XmlReader xrt = XmlReader.Create(new StringReader(transform))
using (XmlReader xri = XmlReader.Create(new StringReader(input))
using (XmlWriter xwo = XmlWriter.Create(sw))
{
   XslCompiledTransform xslt = new XslCompiledTransform();
   xslt.Load(xrt);
   xslt.Transform(xri, xwo);
}
string output = sw.ToString();
查看更多
登录 后发表回答