Click here to Skip to main content
15,867,991 members
Articles / Web Development / XHTML
Tip/Trick

Convert DataTable to XML, XSD, and HTML

Rate me:
Please Sign up or sign in to vote.
4.60/5 (7 votes)
6 Aug 2013CPOL2 min read 79.2K   1.7K   20   5
Converts DataTable to XML, XSD, or HTML using XSLT and C#

What is This?

Have you ever come across a scenario where you had to convert a DataTable to either and HTML or an XML? This tip demonstrates how to do that using C#.

What You Need?

  1. ADO.NET
  2. C#
  3. XML, XPath
  4. An idea of XSLT  

Using the Code

Let's start with a simple DataTable creation. I am not fetching the data from the DB for obvious demonstration purposes. Let's create a Customer table and add a few columns and rows to it.

C#
DataTable table = new DataTable() { TableName = "Customer" };
 
DataColumn keyColumn = table.Columns.Add("Id", typeof(System.Int32));
table.Columns.Add("Name", typeof(System.String));
table.Columns.Add("Address", typeof(System.String));
 
table.PrimaryKey = new DataColumn[] { keyColumn };
 
table.Rows.Add(new object[] { 1, "Customer 1", "Address1" });
table.Rows.Add(new object[] { 2, "Customer 2", "Address2" });
table.Rows.Add(new object[] { 3, "Customer 3", "Address3" });
table.Rows.Add(new object[] { 4, "Customer 4", "Address4" });
table.Rows.Add(new object[] { 5, "Customer 5", "Address5" });
 
table.AcceptChanges();    

The above code creates a table called Customer. Then Adds three columns Id, Name, and Address. Then makes Id as the primary key and then adds a few rows of data.

Now let's convert this DataTable to XML. DataTable has built in overloaded methods WriteXml and WriteXmlSchema using which you can convert the DataTable to either XML or XSD, respectively.

C#
string xmlString = string.Empty;
using (TextWriter writer = new StringWriter())
{
  table.WriteXml(writer);
  xml = writer.ToString();
}  

Moving further, to convert this DataTable to HTML, we need XSLT.

What is XSLT?

XSLT is a language for transforming XML documents into XHTML documents or to other XML documents. It separates the data from formatting. The data is provided via XML and the formatting is decided in XSL. The traversing of XML is done using XPath. The following diagram depicts the scenario:

Image 1

You can apply filters and styles to XSLT. XSLT allows you to define variables, you can have loops, you can have condition checks, and many more ...

The default XSLT generated by Visual Studio template looks like this:

XML
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet> 

This takes XML as input and renders the output in XML. However, you can change this in <xsl:output> node by specifying the method attribute as html. Here is a complete XSLT file used to convert a DataTable to HTML:

XML
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
  <xsl:output method="html" omit-xml-declaration="yes" indent="yes"/>
  
  <xsl:template match="@* | node()">
    <html>
      <body>
        <table>
          <tr>
            <xsl:for-each select="/*/node()">
              <xsl:if test="position()=1">
                <xsl:for-each select="*">
                  <td>
                    <xsl:value-of select="local-name()"/>
                  </td>
                </xsl:for-each>
              </xsl:if>
            </xsl:for-each>
          </tr>
          <xsl:for-each select="*">
            <tr>
              <xsl:for-each select="*">
                <td>
                  <xsl:value-of select="."/>
                </td>
              </xsl:for-each>
            </tr>
          </xsl:for-each>
        </table>
      </body>
    </html>
  </xsl:template>
</xsl:stylesheet>

The above XSLT stylesheet loops through the nodes and adds <tr> and <td>, respectively. As the scope of this tip is not to explain XSLT, let's move to the next part of converting DataTable to HTML. This is a two step process:

  1. First, convert DataTable to XML.
  2. Second, feed this XML to XSLT and get the HTML output.

The first step is discussed above. Now the second step is performed by using the XslCompiledTransform class in the System.Xml.Xsl namespace. This class transforms XML data using an XSLT stylesheet. We just have to use two methods of this class: Load and Transform.

C#
XDocument result = new XDocument();
using (XmlWriter writer = result.CreateWriter())
{
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(templatePath);
xslt.Transform(xmlObj.CreateReader(), writer);
} 

The result contains the final transformed HTML. You can use result.Document.ToString() to get the HTML string from the result.

If You Are Interested!

This shows a basic use of XSLT and conversion of DataTable to HTML. You can also use CSS in HTML for a rich user experience. Please download and see the working copy of the entire story. Smile | :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionTo & From HTML-DataTable Pin
devvvy1-Jan-15 20:03
devvvy1-Jan-15 20:03 
Questionthank you Pin
DANIAL RAVI9-Nov-14 18:25
DANIAL RAVI9-Nov-14 18:25 
QuestionNeed Help From You.. Pin
Kumar Kovuru4-Dec-13 19:52
Kumar Kovuru4-Dec-13 19:52 
AnswerThink this is a tip Pin
Clifford Nelson25-Jul-13 9:41
Clifford Nelson25-Jul-13 9:41 
GeneralRe: Think this is a tip Pin
pramod.hegde25-Jul-13 9:58
professionalpramod.hegde25-Jul-13 9:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.