如何将通用List的内容转换为HTML?

时间:2016-01-04 18:10:02

标签: c# html dom generic-list

我需要将自定义类的通用列表的内容转换为html。例如,如果我在一般列表中存储如下所示的类的值:

public class PlatypusSummary
{
    public String PlatypusName { get; set; }
    public int TotalOccurrencesOfSummaryItems { get; set; }
    public int TotalSummaryExceptions { get; set; }
    public double TotalPercentageOfSummaryExceptions { get; set; }
}

...所以我最终得到了这样的通用列表:

List<PlatypusSummary> _PlatypusSummaryList = null;
. . .
var dbp = new PlatypusSummary
{
    PlatypusName = summary["duckbillname"].ToString(),
    TotalOccurrencesOfSummaryItems = totalOccurrences,
    TotalSummaryExceptions = totalExceptions,
    TotalPercentageOfSummaryExceptions = totalPercentage
};
_PlatypusSummaryList.Add(dbp);

...如何将该通用列表的内容转换为HTML?

1 个答案:

答案 0 :(得分:-1)

这是一种从该列表中生成一些“普通香草”HTML的方法。这可以适用于其他类类型(用您的类替换“PlatypusSummary”)和类成员(替换“PlatypusName”以及类的成员的foreach循环中的其他值):

internal static string ConvertDuckbillSummaryListToHtml(List<PlatypusSummary> _PlatypusSummaryList)
{
    StringBuilder builder = new StringBuilder();
    // Add the html opening tags and "preamble"
    builder.Append("<html>");
    builder.Append("<head>");
    builder.Append("<title>");
    builder.Append("bla"); // TODO: Replace "bla" with something less blah
    builder.Append("</title>");
    builder.Append("</head>");
    builder.Append("<body>");
    builder.Append("<table border='1px' cellpadding='5' cellspacing='0' ");
    builder.Append("style='border: solid 1px Silver; font-size: x-small;'>");

    // Add the column names row
    builder.Append("<tr align='left' valign='top'>");
    PropertyInfo[] properties = typeof(PlatypusSummary).GetProperties();
    foreach (PropertyInfo property in properties)
    {
        builder.Append("<td align='left' valign='top'><b>");
        builder.Append(property.Name);
        builder.Append("</b></td>");
    }
    builder.Append("</tr>");

    // Add the data rows
    foreach (PlatypusSummary ps in _PlatypusSummaryList)
    {
        builder.Append("<tr align='left' valign='top'>");

        builder.Append("<td align='left' valign='top'>");
        builder.Append(ps.PlatypusName);
        builder.Append("</td>");

        builder.Append("<td align='left' valign='top'>");
        builder.Append(ps.TotalOccurrencesOfSummaryItems);
        builder.Append("</td>");

        builder.Append("<td align='left' valign='top'>");
        builder.Append(ps.TotalSummaryExceptions);
        builder.Append("</td>");

        builder.Append("<td align='left' valign='top'>");
        builder.Append(ps.TotalPercentageOfSummaryExceptions);
        builder.Append("</td>");

        builder.Append("</tr>");
    }

    // Add the html closing tags
    builder.Append("</table>");
    builder.Append("</body>");
    builder.Append("</html>");

    return builder.ToString();
}

注意:此代码改编自Sumon Banerjee的“数据表到HTML”代码here