Click here to Skip to main content
15,358,440 members
Articles / Web Development / XHTML
Posted 25 Jul 2013

Tagged as


20 bookmarked

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
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.

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" });

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.

string xmlString = string.Empty;
using (TextWriter writer = new StringWriter())
  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 version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="" 
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="@* | node()">
<xsl:apply-templates select="@* | node()"/>

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 version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl=""
    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()">
            <xsl:for-each select="/*/node()">
              <xsl:if test="position()=1">
                <xsl:for-each select="*">
                    <xsl:value-of select="local-name()"/>
          <xsl:for-each select="*">
              <xsl:for-each select="*">
                  <xsl:value-of select="."/>

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.

XDocument result = new XDocument();
using (XmlWriter writer = result.CreateWriter())
XslCompiledTransform xslt = new XslCompiledTransform();
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 | :)


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


About the Author

Software Developer
India India
No Biography provided

Comments and Discussions

QuestionTo & From HTML-DataTable Pin
devvvy1-Jan-15 20:03
Memberdevvvy1-Jan-15 20:03 
Questionthank you Pin
DANIAL RAVI9-Nov-14 18:25
MemberDANIAL RAVI9-Nov-14 18:25 
QuestionNeed Help From You.. Pin
Kumar Kovuru4-Dec-13 19:52
MemberKumar Kovuru4-Dec-13 19:52 
yes..i created table ...after that am not understanding...if you don't mind then explain after that...
AnswerThink this is a tip Pin
Clifford Nelson25-Jul-13 9:41
MemberClifford 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.