Click here to Skip to main content
Click here to Skip to main content

Convert DataTable to XML, XSD, and HTML

, 6 Aug 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
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" });
 
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.

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:

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

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)

Share

About the Author

pramodhegde88
Software Developer
India India
No Biography provided

Comments and Discussions

 
Questionthank you PingroupDANIAL RAVI9-Nov-14 19:25 
QuestionNeed Help From You.. PinprofessionalKumar Kovuru4-Dec-13 20:52 
AnswerThink this is a tip PinmemberClifford Nelson25-Jul-13 10:41 
GeneralRe: Think this is a tip Pinmemberpramodhegde8825-Jul-13 10:58 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.1411022.1 | Last Updated 6 Aug 2013
Article Copyright 2013 by pramodhegde88
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid