The main purpose to use XSLT in C# for making your application faster while rendering from server.
this is the following code on how to use simple xslt files in ur aspx page by using c#.
This is only for rendering a static data only not dynamic means the xslt contains hard coded data only.
This can be handy when u r using any header or footer or any portion of your application which is a bit heavier and taking more time to load.
Step 1:
Create a file named as Demo.xsl and put the below code.
<?xml version=”1.0″ encoding=”UTF-8″ ?>
<xsl:stylesheet version=”1.0″ xmlns:xsl=”http://www.w3.org/1999/XSL/Transform”>
<xsl:output method=”html”/>
<xsl:template match=”/”>
<div>
Test xslt page
</div>
<div>
<div>
Demo text here
</div>
<div>
Write ur required html here.
</div>
</div>
</xsl:template>
</xsl:stylesheet>
Step 2:
Create a page TestXSLT.aspx and paste the below code
<form id=”form1″ runat=”server”>
<div>
Head
</div>
<div id=”divContent” runat=”server”>
</div>
</form>
Step 3:
Here we are rendering the Demo.xsl and add the content to the div id having divContent.
So in the page load of TestXSLT.aspx.cs write the below code and followed by the next methods also.
protected void Page_Load(object sender, EventArgs e)
{
string html = GetPageHTML().Replace(“��”, “”);
divContent.InnerHtml = html;
}
private string GetPageHTML()
{
try
{
string xsltFileName = “Demo.xsl“;
string xmlData = “”;
string fullXsltFilePath = Server.MapPath(xsltFileName); // check properly the xsl filepath
XmlSerializer xs = new XmlSerializer(xmlData.GetType());
string xmlString;
using (StringWriter swr = new StringWriter())
{
xs.Serialize(swr, xmlData);
xmlString = swr.ToString();
}
var xd = new XmlDocument();
xd.LoadXml(xmlString);
var xslt = new System.Xml.Xsl.XslCompiledTransform();
xslt.Load(fullXsltFilePath);
var stm = new MemoryStream();
xslt.Transform(xd, null, stm);
stm.Position = 1;
var sr = new StreamReader(stm);
return sr.ReadToEnd();
}
catch { return null; }
}
In the above code Replace(“��”, “”) is used because when ur rendering a blank xml then the stream reader returns this “��” charcters at the beginning of the returned string, so to avoid that this Replace method is used.