How To Use XSLT in .Net

Posted In Tutorials - By NitiN Kumar Jain On Saturday, November 29th, 2008 With 0 Comments






Pin It


It is fairly easy to use XSL transform in .Net, go on reading to know how.

System provides you System.Xml.Xsl.XslCompiledTransform class to do direct processing for you.

We have loaded our xml in a stream object. We use XmlTextReader to read the xml from the stream object.

We also use a StreamWriter object that is responsible for writing the transformed form of the supplied xml to a stream. This stream writer is associated with a memory stream object which is actually holding the transformed data.

We can call Load method of the XslCompiledTransform to load the XSL file and then can call Transform method providing it an input xml text reader and output as a stream writer.

Ensure to set the position of the output stream to 0 before accessing it.

I have loaded the output memory stream in web browser control.

See an example below:

using System.IO;
using System.Xml;
using System.Xml.Xsl;
……
……
XmlTextReader xmlReader;
XslCompiledTransform xslTrans = new XslCompiledTransform();
MemoryStream memStream = new MemoryStream();
StreamWriter streamWriter = new StreamWriter(memStream);

messageStream.Position = 0;
xmlReader = new XmlTextReader(messageStream);

xslTrans.Load(XslFilePath);
xslTrans.Transform(xmlReader, null, streamWriter);
memStream.Position = 0;
webBrowserMessageDetail.DocumentStream = memStream;
……
……

-NKJ