How to transform XML into XHTML using XSLT through XslCompiledTransform class


XSLT (XSL Transformations):

XML - based language used for the transformation of XML documents into HTML documents. The transformation may happen dynamically either on the client or on the server.

XslCompiledTransform class:

The XslCompiledTransform class is an XSLT processor that supports the XSLT 1.0 syntax. It is a new implementation and includes performance gains when compared to the obsolete XslTransform class.

Example :

"Data.Xml" file

<xml version="1.0" ?>
<books>
<book>
<id> 1 <id>
<name> XML Concepts <name>
<author > AUTHOR1 < author>
<price > 40.00 <price>
<book>
< book>
< id> 2 <id>
<name> Website Programmingname <name>
<author> AUTHOR2 <author>
<price> 50.00 <price >
<book>
<book>
<id> 3 <id>
<name> LINQ Concepts <name>
<author> AUTHOR3 <author>
<price> 10.00 <price>
<book>
<books>


Data.XSLT file

<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="/">
<html>
<head>
<title>How to use XslCompiledTransform Class in asp.net</title>
</head>
<body>
<h2 style="color:DarkOrange; font-style:italic;">
XSLT - Using XslCompiledTransform
&lt;/h2>
<hr width="370" align="left" color="Orange" />
<br />
<table border="1" cellpadding="5" cellspacing="0" bordercolor="CornFlowerBlue">
<tr bgcolor="DodgerBlue" style="color:White; font-weight:bold">
<td align="center">Name of Book</td>
<td>Name of Author</td>
<td>Book Price</td>
</tr>
<xsl:for-each select="books/book">
<tr bgcolor="Snow" style="color:Black; font-weight:normal; font-style:italic;">
<td height="10">
<xsl:value-of select="name"/>
</td>
<td height="10">
<xsl:value-of select="author"/>
</td>
<td height="10" style="font-weight:bold;">
<xsl:value-of select="price"/>
</td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
<xsl:template>
<xsl:stylesheet>




Transform XML into HTML using XslCompiledTransform class:




using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;

public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string xmlFilePath = Request.PhysicalApplicationPath + @"App_Data\Data.xml";
string xsltPath = Request.PhysicalApplicationPath + @"App_Data\Data.xslt";
XPathDocument xPathDoc = new XPathDocument(xmlFilePath);
XslCompiledTransform transform = new XslCompiledTransform();
transform.Load(xsltPath);
transform.Transform(xPathDoc, null, Response.Output);
}
}




Output of Above page is :

No comments: