使用 c# 编辑 HTML 并替换其中的某些文本

Sae*_*ani 5 html c# string templates replace

在我的 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>
Run Code Online (Sandbox Code Playgroud)

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

任何想法、代码片段、tuturial 链接等...都将被采纳!

Nak*_*nch 3

使用正则表达式或快速而肮脏的替换来解析 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;
                }
            }
Run Code Online (Sandbox Code Playgroud)