Monday, April 14, 2008

Create Html table from datasets

If you're looking for an elegant way to convert your dataset to an html table you can achieve that by using an xslt transformation on the dataset xml output.

Use this xslt to transform your xml dataset:


<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

<xsl:output method="html" version="4.0"/>

<xsl:template match="NewDataSet">
<div>
<table border="1">
<xsl:for-each select="/NewDataSet/TABLENAME0" >
<xsl:call-template name="DoLine" />
</xsl:for-each>
</table>
<br />
<table border="1">
<xsl:for-each select="/NewDataSet/TABLENAME1" >
<xsl:call-template name="DoLine" />
</xsl:for-each>
</table>
</div>
</xsl:template>

<xsl:template name="DoLine" >
<xsl:if test="position()=1">
<tr>
<td>
<xsl:value-of select="local-name()" />
</td>
</tr>
<tr class="header" >
<xsl:for-each select="./*">
<td>
<xsl:value-of select="local-name()" />
</td>
</xsl:for-each>
</tr>
</xsl:if>

<tr class="row" >
<xsl:for-each select="./*">
<td>
<xsl:value-of select="." />
</td>
</xsl:for-each>
</tr>
</xsl:template>

</xsl:stylesheet>



Here is the code that converts the dataset to an html table:

DataSet ds = db.ExecuteDataSet(dbc, transaction);
ds.Tables[0].TableName = "Table1";
ds.Tables[1].TableName = "Table2";
ds.Tables[2].TableName = "Table3";
XmlDataDocument dataDocument = new XmlDataDocument(ds);
XslCompiledTransform xslTransform = new XslCompiledTransform();
XmlDocument xmlDocument = new XmlDocument();
string xslSource = Properties.Resources.XslDatasetXmlToHtmlTable;
xslSource = xslSource.Replace("TABLENAME0", ds.Tables[0].TableName); xslSource = xslSource.Replace("TABLENAME1", ds.Tables[1].TableName); xslSource = xslSource.Replace("TABLENAME2", ds.Tables[2].TableName); xmlDocument.LoadXml(xslSource);
xslTransform.Load(xmlDocument);
StringBuilder stringBuilder = new StringBuilder();
XmlWriter xmlWriter = XmlWriter.Create(stringBuilder);
xslTransform.Transform(dataDocument, xmlWriter);
xmlWriter.Flush();

No comments: