Tuesday, 7 June 2011

XSLT in ASP.Net


cdcatalog.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<catalog>
  <cd>
    <title>Empire Burlesque</title>
    <artist>Bob Dylan</artist>
    <country>USA</country>
    <company>Columbia</company>
    <price>10.90</price>
    <year>1985</year>
  </cd>
.
.
</catalog>

cdcatalog.xsl
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
  <html>
  <body>
  <h2>My CD Collection</h2>
  <table border="1">
    <tr bgcolor="#9acd32">
      <th align="left">Title</th>
      <th align="left">Artist</th>
    </tr>
    <xsl:for-each select="catalog/cd">
    <tr>
      <td><xsl:value-of select="title" /></td>
      <td><xsl:value-of select="artist" /></td>
    </tr>
    </xsl:for-each>
  </table>
  </body>
  </html>
</xsl:template>
</xsl:stylesheet>


abc.aspx.cs Page
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;

private void ShowXmlWithXSLT()
{
  XmlDocument docXml = new XmlDocument();
        XslCompiledTransform docXsl = new XslCompiledTransform();
        string XMLFileNameWithPath = string.Empty;
        string XSLTFileNameWithPath = string.Empty;

        try
        {
            // Load xml Documenet
            XMLFileNameWithPath = Server.MapPath(“cdcatalog.xml”);
            if (File.Exists(XMLFileNameWithPath))
            {
                docXml.Load(XMLFileNameWithPath);

                // Load the XSLT
                XSLTFileNameWithPath = Server.MapPath(“cdcatalog.xsl”);
    docXsl.Load(XSLTFileNameWithPath);

                // Set the Html to the page control to display
                System.IO.StringWriter writer = new System.IO.StringWriter();
                docXsl.Transform(docXml, null, writer);

                // Set the Innerhtml for the control to shoe the html           
                DivExample.InnerHtml = writer.ToString();               
        }
        catch (Exception)
        {
        }
}

No comments:

Post a Comment