Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Converting XML string to HTML Table

5.00/5 (1 vote)
19 Dec 2012CPOL 43.1K  
This article describes about converting an XML string to a HTML table.

Introduction

Many web developers come across the scenario of displaying XML content on a webpage. And sometimes its nice to present it in a tabular format rather than the raw XML view. Below is a small recursive function which can help you converting XML string to a HTML Table string.

Using the code 

This function takes a string (XML content) as input and returns a string (HTML Table). Once we have the output string with the HTML content, it's easy to render it on a web page. For example, we can simply assign the output string to a label on the web page to have the tabular view. 

C#
protected string ConvertXmlToHtmlTable(string xml)
{
  StringBuilder html = new StringBuilder("<table align='center' " + 
     "border='1' class='xmlTable'>\r\n");
  try
  {
      XDocument xDocument = XDocument.Parse(xml);
      XElement root = xDocument.Root;

      var xmlAttributeCollection = root.Elements().Attributes();


      foreach (var ele in root.Elements())
      {
          if (!ele.HasElements)
          {
              string elename = "";
              html.Append("<tr>");

              elename = ele.Name.ToString();

              if (ele.HasAttributes)
              {
                  IEnumerable<XAttribute> attribs = ele.Attributes();
                  foreach (XAttribute attrib in attribs)
                  elename += Environment.NewLine + attrib.Name.ToString() + 
                    "=" + attrib.Value.ToString();
              }

              html.Append("<td>" + elename + "</td>");
              html.Append("<td>" + ele.Value + "</td>");
              html.Append("</tr>");
          }
          else
          {
              string elename = "";
              html.Append("<tr>");

              elename = ele.Name.ToString();

              if (ele.HasAttributes)
              {
                  IEnumerable<XAttribute> attribs = ele.Attributes();
                  foreach (XAttribute attrib in attribs)
                  elename += Environment.NewLine + attrib.Name.ToString() + "=" + attrib.Value.ToString();
              }

              html.Append("<td>" + elename + "</td>");
              html.Append("<td>" + ConvertXmlToHtmlTable(ele.ToString()) + "</td>");
              html.Append("</tr>");
          }
      }

      html.Append("</table>");
  }
  catch (Exception e)
  {
      return xml;
      // Returning the original string incase of error.
  }
  return html.ToString();
}

License

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