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.
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;
}
return html.ToString();
}