Jasinski Technical Wiki


Home Page
All Pages

Quick Search
Advanced Search »

Contributor Links

Create a new Page
File Management
Your Profile

Other Wiki Sections



Changing XSL Code on the Fly - .NET Framework

Modified on Thu, Nov 05, 2009, 10:11 PM by Administrator Categorized as XML, XSL, and XPath, ┬Ě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.

public static string TransformXml(string inputXml, string xslVirtualFile)
    //- Load XSL Transformation -----------------------------------------------------------
    xslVirtualFile = HttpContext.Current.Server.MapPath(xslVirtualFile);
    XslCompiledTransform xslTransform = new XslCompiledTransform();
    StreamReader streamReader = new StreamReader(xslVirtualFile);
    string xsl = streamReader.ReadToEnd();
    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();

ScrewTurn Wiki version Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2023, Patrick Jasinski.