How to use XSLT to generate dynamic XML

Hi Guys,

Long time from my last post, what can I say, I have been busy 😛 Ok but now here is a quick sample about how to use XSLT to generate dynamic HTML and maybe create emails to send, to create XML files, or generate a entire or partial page to render, basically is the way you want to generate dynamic content.

In case you don’t know what is XSLT please read this page (thanks Wikipedia!), and maybe take a look of some other examples to understand how big can be in case you want to be more technical please check the W3C document

I will explain a very basic sample of how to use it with C# but please tell me in your comments any doubt or problem you have.

To do this example I created a new Web Site project in VS with the default settings,

The first step is to work with the XSLT template, to do this we need to define what will be the master template and what sections will be generated dynamically, an example of a simple XSLT template could be something like this:

<?xml version="1.0" encoding="utf-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/DataSet">
    <xsl:for-each select="Table">
      <xsl:variable name="blogUrl">
        <xsl:value-of select="BlogUrl"/>
      </xsl:variable>
      <xsl:variable name="imagesRootUrl">
        <xsl:value-of select="ImagesRootUrl"/>
      </xsl:variable>

      <h1>
        <xsl:value-of select="MainTitle"/>
      </h1>
      <xsl:choose>
        <xsl:when test="IsMonday">
          Today is Monday!
        </xsl:when>
        <xsl:otherwise>
          Today is not Monday!
        </xsl:otherwise>
      </xsl:choose>
      <br/>
      <img src="{$imagesRootUrl}07fig01.gif" alt="This is an image" width="550" height="374" />
      <br/>
      <p>
        Please visit my <a href="{$blogUrl}">blog</a>
      </p>
      <span>©2012 Alejandro Carmona</span>
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>

As you can see this XSLT template has some static text and some dynamic text too, this dynamic text will be generated with the XSLT Transform from C#.

The second step is to create a data source from where we will get the data to Transform the XSLT Template to a XML, in this case we’ll use a DataSet in C# like this:

DataSet DataSource = new DataSet("DataSet");
DataTable DataTable = DataSource.Tables.Add("Table");

DataColumn pkCol = DataTable.Columns.Add("Id", typeof(int));
DataTable.Columns.Add("BlogUrl", typeof(string));
DataTable.Columns.Add("ImagesRootUrl", typeof(string));
DataTable.Columns.Add("MainTitle", typeof(string));
DataTable.Columns.Add("IsMonday", typeof(bool));              
DataTable.PrimaryKey = new DataColumn[] { pkCol };

DataRow dr = DataTable.NewRow();

dr["Id"] = 1;
dr["BlogUrl"] = @"https://alejandrodotnet.wordpress.com";
dr["ImagesRootUrl"] = @"http://www.webreference.com/authoring/languages/xml/aspnet/chap7/";
dr["MainTitle"] = "Hello World from XSLT";
dr["IsMonday"] = DateTime.Today.DayOfWeek == DayOfWeek.Monday;

DataTable.Rows.Add(dr);

The third step is to Transform the XSLT using the Template and our DataSource to generate the output

XmlDataDocument xmlLocations = new XmlDataDocument(DataSource);
XslCompiledTransform xslTran = new XslCompiledTransform();

string template = string.Empty;
TextWriter sw;

using (XmlTextReader xmlReader = new XmlTextReader(Server.MapPath("~/App_Data/SampleTemplate.xml")))
{
    xslTran.Load(xmlReader, null, null);

    StringBuilder sb = new StringBuilder();
    sw = new StringWriter(sb);

    xslTran.Transform(xmlLocations, null, sw);
}

Finally the last step is to show the result (I’m using a Literal Control to display the result)

litResponse.Text = sw.ToString();

The final result looks like this:

Now you have the basic knowledge to use XSLT,

Here is the VS project in case you want to try https://skydrive.live.com/redir.aspx?cid=842c5fff52cea6ab&resid=842C5FFF52CEA6AB!1221&parid=root

Advertisements

2 thoughts on “How to use XSLT to generate dynamic XML

  1. ali med says:

    ok , is very good
    can you help me
    write me inf2050@yahoo.fr
    thamks

  2. Palavesh says:

    Hi,
    The VS project link is broken, can you please update it.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: