Using XML and XSLT

XML Stylesheet Transformation(XSLT) is defined as a language for converting XML documents to other document formats.

XSLT processors parse the input XML document, as well as the XSLT stylesheet and then process the instructions found in the XSLT stylesheet, using the elements from input XML document. During the processing of the XSLT instructions, a structured XML output is created.

We are going to perform the transformation using classes of .NET Framework.The class we are going to use are

The XslTransform class, found in the System.Xml.Xsl namespace, is the XSLT processor that implements
the XSLT version 1.0 recommendation.

In order to perform a transformation using XslTransform, first create an XslTransform object and load it with
the desired XSLT document (by calling Load). The Load method of XslTransform class loads the XSL Stylesheet
from disk called xsltDoc. Finally, the transform is executed by calling Transform method of the XslTransform class object.

Let us look this with an example.


<?xml version="1.0" encoding="utf-8" ?> 
name>Cereal Milk</name>
cost>R.S 100</cost>
name>Badam Pista</name>
cost>R.S 230</cost>

We are now going to frame an XSLT document for the above XML.

<?xml version="1.0" encoding="ISO-8859-1" ?>

      <xsl:stylesheet version="1.0" xmlns:xsl="">

            <xsl:template match="/">

                  <table border="1">





                        <xsl:for-each select="Products/product">



                                    <br><xsl:value-of select="name"/></br>



                                    <br><xsl:value-of select="cost"/></br>







Now let us look ata the transformation part

We are using the XmlUrlResolver and XslTransform class to perform the transformation.

XmlUrlResolver class is used to resolve external XML resources such as entities, document type definitions (DTDs), or schemas. It is also used to process include and import elements found in Extensible StyleSheet
Language (XSL) stylesheets or XML Schema Definition language (XSD) schemas.

XslTransform Class Methods

  • Load()
    Loads an XSLT document. This method can accept an XmlReader, a document URL, or a variety of other objects.

  • Transform()
    The Transform() method is overloaded and can therefore accept a variety of parameters.

The most common form of the method that you'll likely use in your ASP.NET applications is shown next (check the .NET SDK for the other overloaded versions of the method):
Now let us look at our code,

XmlUrlResolver resolver = new XmlUrlResolver( );
resolver.Credentials = System.Net.CredentialCache.DefaultCredentials;
XslTransform xsltrans=new XslTransform();

When u look at the output,

Name Price
Cereal Milk R.S 100
Badam Pista R.S 230

So now having the knowledge of creating an XSLT document and perform the transformation, you can even create a webpage using an xml file.

Up Next
    Ebook Download
    View all
    View all