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

时间:2011-04-28 10:22:56

标签: c# html 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>

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

任何想法,代码片段,指向tuturial等的链接......都会受到关注!

3 个答案:

答案 0 :(得分:2)

使用正则表达式或快速而脏的替换来解析HTML有很多危险。如果HTML已经被正确“准备好”,那么很多事情都会出错(这是100%确定性的难以理解的事情。)在Milde的答案中提到的HTML敏捷包是一个很好的方法,但它可能感觉像是使用了大锤要打开坚果。

但是,如果您对将要解析的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;
                }
            }

答案 1 :(得分:1)

查看HTML Agility Pack

  

它是一个.NET代码库,允许您解析“out of the web”HTML文件。解析器非常容忍“真实世界”格式错误的HTML。对象模型与提出System.Xml非常相似,但对于HTML文档(或流)。

答案 2 :(得分:0)

看一下剃须刀模板引擎 http://razorengine.codeplex.com/