I'm trying to convert a two dimension list of string to an html table. I did this who does the job :
public string htmlTableFromTwoDimensionList(List<List<string>> list)
{
XDocument xDocument = new XDocument(new XElement("table"));
XElement xTable = xDocument.Element("table");
foreach(List<string> row in list)
{
XElement xRow = new XElement("tr");
foreach(string col in row)
{
if (list.First() == row) xRow.Add(new XElement("th", col));
else xRow.Add(new XElement("td", col));
}
xTable.Add(xRow);
}
return xDocument.ToString();
}
But now, i learn that the string can be some html. So i would like to parse it if it's html or use a string if it's not. I tried to do something like that, without success :
public string htmlTableFromTwoDimensionList(List<List<string>> list)
{
XDocument xDocument = new XDocument(new XElement("table"));
XElement xTable = xDocument.Element("table");
foreach(List<string> row in list)
{
XElement xRow = new XElement("tr");
foreach(string col in row)
{
XElement content;
string text = "";
// tcheck if content is html or text :
try
{
content = XElement.Parse(col);
}
catch
{
text = col;
}
if (list.First() == row) xRow.Add(new XElement("th", string.IsNullOrEmpty(text) ? content : text));
else xRow.Add(new XElement("td", string.IsNullOrEmpty(text) ? content : text));
}
xTable.Add(xRow);
}
return xDocument.ToString();
}
But I'm not even sure to use try catch in this situation. Any idea to do that properly ?