Changing XSL Code on the Fly - .NET Framework

The following code demonstrates how to change XSL code on the fly. First, XSL code is marked up with tags — "{appRootUrl}" in this case — and saved in an XSL file. Then the following procedure is called to transform the XML via the XSL in the file. The XSL code, in turn, is changed on the fly: the instances of "{appRootUrl}" are replaced with Helper.ApplicationRootUrl.

Note: The Helper.ApplicationRootUrl procedure can be found here.

{copytext|div1}
public static string TransformXml(string inputXml, string xslVirtualFile)
{
    //- Load XSL Transformation -----------------------------------------------------------
    xslVirtualFile = HttpContext.Current.Server.MapPath(xslVirtualFile);
    XslCompiledTransform xslTransform = new XslCompiledTransform();
    xslTransform.Load(xslVirtualFile);
    StreamReader streamReader = new StreamReader(xslVirtualFile);
    string xsl = streamReader.ReadToEnd();
    streamReader.Close();
    xsl = xsl.Replace("{appRootUrl}", Helper.ApplicationRootUrl);
    MemoryStream ms = new MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes(xsl));
    xslTransform.Load(new XmlTextReader(ms));

    //- Load XML Data ---------------------------------------------------------------------
    StringReader sr = new StringReader(inputXml);
    XmlReader xr = new XmlTextReader(sr);
    StringWriter sw = new StringWriter();
    XmlWriter xw = new XmlTextWriter(sw);

    //- Transform and Output Data ---------------------------------------------------------
    xslTransform.Transform(xr, xw);
    return sw.ToString();
}