在我的C#WinForms程序中,我想生成一个HTML格式的报告。我现在正在使用StringBuilder和TextWriter并编写所有html代码并将文件另存为HTML。它正在工作,但是我想改善工作流程。

所以我的想法是要有一个包含某些文本的HTML模板,这些文本将被一个特殊的标签或其他东西代替(我之前使用过Smarty模板,所以我的意思是这样)。

想象一下下面的HTML代码:

        <tr>
        <td style="height: 80px; background-color:#F4FAFF">
        <span class="testPropertiesTitle">Test Properties</span>
        <br /><br />
        <span class="headerComment"><b>Test Mode:</b>&nbsp;[TestMode]</span>
        <br /><br />
        <span class="headerComment"><b>Referenced DUT:</b>&nbsp;[RefDUT]</span>
        <br /><br />
        <span class="headerComment"><b>Voltage Failure Limit:</b>&nbsp;[VoltageLimit]</span>
        <br /><br />
        <span class="headerComment"><b>Current Failure Limit:</b>&nbsp;[CurrentLimit]</span>
        <br /><br />
        <span class="headerComment"><b>Test Mode:</b>[TestMode]&nbsp;</span>
        </td>
    </tr>

因此,基本上我想做的是用我的C#程序中生成的某些字符串替换上面html中[]之间的文本。

任何想法,代码段,教程的链接等都将适用!

最佳答案

用正则表达式或快速而肮脏的替换来解析HTML存在太多危险。如果正确地“准备了” HTML,那么很多事情都会出错(这是100%确定性的事情。)Milde的答案中提到的HTML Agility Pack是一个很好的解决方法,但是可能感觉像是使用了大锤将螺母拆开。

但是,如果您对将要解析的HTML很有信心,那么以下内容应该可以使您快速入门:

     string strTextToReplace = "<tr><td style=\"height: 80px; background-color:#F4FAFF\"> <span class=\"testPropertiesTitle\">Test Properties</span><br /><br /><span class=\"headerComment\"><b>Test Mode:</b>&nbsp;[TestMode]</span><br /><br /><span class=\"headerComment\"><b>Referenced DUT:</b>&nbsp;[RefDUT]</span><br/><br/><span class=\"headerComment\"><b>Voltage Failure Limit:</b>&nbsp;[VoltageLimit]</span><br /><br /><span class=\"headerComment\"><b>Current Failure Limit:</b>&nbsp;[CurrentLimit]</span><br /><br /><span class=\"headerComment\"><b>Test Mode:</b>[TestMode]&nbsp;</span>  </td></tr>";

            Regex re = new Regex(@"\[(.*?)\]");
            MatchCollection mc = re.Matches(strTextToReplace);
            foreach (Match m in mc)
            {
                switch (m.Value)
                {
                    case "[TestMode]":
                        strTextToReplace = strTextToReplace.Replace(m.Value, "-- New Test Mode --");
                        break;
                    case "[RefDUT]":
                        strTextToReplace = strTextToReplace.Replace(m.Value, "-- New Ref DUT --");
                        break;
                    //Add additional CASE statements here
                    default:
                        break;
                }
            }

10-07 19:30
查看更多