如何使用 StringBuilder 将样式定义附加到字符串中的 <TD> 标记?

How to append style definition to <TD> tag within string using StringBuilder?

我正在从 C# 类型的列表构建 HTML table。到目前为止构建 table 工作正常,但我现在需要将样式附加到构建 table.

的字符串中的 <TD> 标记之一

我尝试的是在使用字符串生成器附加到字符串时,将样式定义简单地添加到 TD。但是我在使用样式定义时遇到语法错误。

问题: 如何将样式定义附加到字符串中的标记?

我使用 String Builder 字符串实例创建 table 主体:

StringBuilder releaseStatusTableBodyData = new StringBuilder();

然后在table字符串中添加一行和一列。从样式中删除双引号并没有删除显示的语法错误:

        foreach(var row in releaseStatusList)
        {

            //for each record create a new table row
            releaseStatusTableBodyData.Append("<TR>\n");


            releaseStatusTableBodyData.Append("<TD style=""bgcolor: green;"">");  //added the style to the TD here, but get syntax error on the style telling me ) is required.
            releaseStatusTableBodyData.Append(row.Days_Owned);
            releaseStatusTableBodyData.Append("</TD>");



            releaseStatusTableBodyData.Append("</TR>\n"); //end of row

        }

在字符串的开头放置逐字文字 (@)。

releaseStatusTableBodyData.Append(@"<TD style=""background-color: green;"">");
                                 ^^^

从某些背景来看,在字符串中添加转义字符串似乎更容易,但对我来说这更容易阅读。

可能也值得尝试 HtmlTextWriter。它本质上是在做同样的事情,并提供一些特定于 HTML.

的帮助
string html;
using (var sw = new StringWriter())
using (var hw = new HtmlTextWriter(sw))
{
    hw.RenderBeginTag(HtmlTextWriterTag.Tr);
    hw.AddStyleAttribute(HtmlTextWriterStyle.BackgroundColor, "green");
    hw.RenderBeginTag(HtmlTextWriterTag.Td);
    hw.RenderEndTag();
    hw.RenderEndTag();
    html = sw.ToString();
}

有点奇怪的是,您必须在 呈现 Td 标签之前添加样式属性

好处是您可以使用大量预定义的标签和样式名称常量。如果您需要一些条件逻辑,这会容易得多。

hw.RenderBeginTag(HtmlTextWriterTag.Tr);
if(makeThisGreen)
    hw.AddStyleAttribute(HtmlTextWriterStyle.BackgroundColor, "green");
if(makeThisBold)
    hw.AddStyleAttribute(HtmlTextWriterStyle.FontWeight, "bold");
hw.RenderBeginTag(HtmlTextWriterTag.Td);
hw.RenderEndTag();
hw.RenderEndTag();

使用 StringBuilder 当你到达第二个条件时,你必须检查你是否已经启动了 style 属性以确保你没有创建它两次。然后您必须检查这些条件中的任何一个是否为真,以便您知道是否将结束引号添加到 style 属性。 (或者您可以创建一个方法来为您完成所有这些工作。)但是这项工作已经在 HtmlTextWriter class 中完成了。

您还可以使用 WriteBeginTag(string)WriteEndTag(string),它们可以让您更明确地控制编写标签。

foreach(var row in releaseStatusList) {

 //for each record create a new table row
 releaseStatusTableBodyData.Append("<TR>\n").Append("<TD style=color:green>").Append(row.Days_Owned).Append("</TD>").Append("</TR>\n");

}