[英]Add dynamically a string or an XElement as child to XElement
我正在尝试将二维字符串列表转换为 html 表。 我做了这个谁做的工作:
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();
}
但是现在,我了解到该字符串可以是一些 html。所以如果它是 html,我想解析它,如果不是,我想使用一个字符串。 我试图做类似的事情,但没有成功:
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();
}
但我什至不确定在这种情况下使用 try catch。 有什么想法可以正确地做到这一点吗?
这是一个解决方案,可能不是最好的,带有一些示例输入:
class Program
{
static void Main(string[] args)
{
List<List<string>> table = new List<List<String>>{
new List<String> { "1d", "Client", "some html", "Date", "col n"},
new List<String> { "1", "Client 1","<a href=\"https://www.google.com\">google</a>","31/12/2022", "some content ..." },
new List<String> { "2", "Client 2","<a href=\"https://www.google.com\">google</a>","31/12/2022", "some content ..." },
new List<String> { "3", "Client 3","<a href=\"https://www.google.com\">google</a>","31/12/2022", "some content ..." },
};
Console.Write(htmlTableFromTwoDimensionList(table));
Console.Read();
}
public static 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 htmlCel;
if (list.First() == row) htmlCel = new XElement("th");
else htmlCel = new XElement("td");
XElement content;
try
{
content = XElement.Parse(col);
htmlCel.Add(content);
}
catch
{
htmlCel.Add(col);
}
xRow.Add(htmlCel);
}
xTable.Add(xRow);
}
return xDocument.ToString();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.