How to transform XML as a string w/o using files in .NET?
c#, xml, xslt
Solution
Here's what I went with. It's a combination of your answers. I voted up the answers that inspired this:
string output = String.Empty;
using (StringReader srt = new StringReader(xslInput)) // xslInput is a string that contains xsl
using (StringReader sri = new StringReader(xmlInput)) // xmlInput is a string that contains xml
{
using (XmlReader xrt = XmlReader.Create(srt))
using (XmlReader xri = XmlReader.Create(sri))
{
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(xrt);
using (StringWriter sw = new StringWriter())
using (XmlWriter xwo = XmlWriter.Create(sw, xslt.OutputSettings)) // use OutputSettings of xsl, so it can be output as HTML
{
xslt.Transform(xri, xwo);
output = sw.ToString();
}
}
}
Note: this statement is required in the xsl, in order to output as HTML:
<xsl:output method="html" omit-xml-declaration="yes" />
Problem
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.