Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Convert DataTable to XML, XSD, and HTML

0.00/5 (No votes)
6 Aug 2013 1  
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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here