Thursday, February 23, 2012

How to convert XML to an HTML table In C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace ConsoleTestApps
{
///
/// takes in well structured xml from something like
/// SELECT * FROM testTable AS XML AUTO
/// where all the elements have identical attribues
/// and creates an HTML table
///
/// collection of xml elements all with the same attributes
/// HTML table with class of 'xmlTable'

class  XmlToHtml
{
public string ConvertXmlToHtmlTable(string xml)
{
XDocument xDocument = XDocument.Parse("" + xml + "");
XElement root = xDocument.Root;
if (root == null || root.Elements().Count() == 0) return "Empty";
var xmlAttributeCollection = root.Elements().First().Attributes();
StringBuilder html = new StringBuilder("\r\n");
foreach (var attribute in xmlAttributeCollection)
{
html.Append("");
}
html.Append("");
foreach (XElement element in root.Descendants())
{
html.Append("\r\n");
foreach (XAttribute attrib in element.Attributes())
{
html.Append("");
}
html.Append("");
}
html.Append("
" + attribute.Name + "
" + attrib.Value + "
");
return html.ToString();
}
}
}

0 comments:

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Powered by Code Imagine