C# 使用c编辑HTML并替换其中的某些文本#
在我的C#WinForms程序中,我想生成一个HTML格式的报告。我现在做的是使用StringBuilder和TextWriter编写所有html代码,并将文件另存为html。它正在工作,但我想加强工作流程 所以我的想法是使用一个HTML模板,其中包含一些文本,这些文本将被一个特殊的标记或其他东西所取代(我以前使用过Smarty模板,所以我的意思是类似的) 想象一下下面的HTML代码:C# 使用c编辑HTML并替换其中的某些文本#,c#,html,string,templates,replace,C#,Html,String,Templates,Replace,在我的C#WinForms程序中,我想生成一个HTML格式的报告。我现在做的是使用StringBuilder和TextWriter编写所有html代码,并将文件另存为html。它正在工作,但我想加强工作流程 所以我的想法是使用一个HTML模板,其中包含一些文本,这些文本将被一个特殊的标记或其他东西所取代(我以前使用过Smarty模板,所以我的意思是类似的) 想象一下下面的HTML代码: <tr> <td style="height: 80px;
<tr>
<td style="height: 80px; background-color:#F4FAFF">
<span class="testPropertiesTitle">Test Properties</span>
<br /><br />
<span class="headerComment"><b>Test Mode:</b> [TestMode]</span>
<br /><br />
<span class="headerComment"><b>Referenced DUT:</b> [RefDUT]</span>
<br /><br />
<span class="headerComment"><b>Voltage Failure Limit:</b> [VoltageLimit]</span>
<br /><br />
<span class="headerComment"><b>Current Failure Limit:</b> [CurrentLimit]</span>
<br /><br />
<span class="headerComment"><b>Test Mode:</b>[TestMode] </span>
</td>
</tr>
测试特性
测试模式:[测试模式]
参考DUT:[参考DUT]
电压故障极限:[电压极限]
当前故障限制:[CurrentLimit]
测试模式:[测试模式]
所以基本上我想做的是用我的C#程序中生成的某些字符串替换上面html中[]之间的文本
任何想法,代码片段,到tuturial的链接等等。。。将被告知 看看razor模板引擎 看一下: 它是一个.NET代码库,允许您解析“web外”HTML文件。解析器对“真实世界”格式错误的HTML非常宽容。对象模型与System.Xml非常相似,但适用于HTML文档(或流)
使用正则表达式或快速脏替换解析HTML非常危险。如果HTML已经正确地“准备好”(这是一件很难100%确定地做到的事情),那么很多事情都可能出错。在Mide的回答中提到的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> [TestMode]</span><br /><br /><span class=\"headerComment\"><b>Referenced DUT:</b> [RefDUT]</span><br/><br/><span class=\"headerComment\"><b>Voltage Failure Limit:</b> [VoltageLimit]</span><br /><br /><span class=\"headerComment\"><b>Current Failure Limit:</b> [CurrentLimit]</span><br /><br /><span class=\"headerComment\"><b>Test Mode:</b>[TestMode] </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;
}
}
string strTextToReplace=“测试属性
测试模式:[TestMode]
参考DUT:[RefDUT]
电压故障限值:[VoltageLimit]
电流故障限值:[CurrentLimit]
测试模式:[TestMode];
正则表达式re=新正则表达式(@“\[(.*?\]);
MatchCollection mc=重新匹配(strTextToReplace);
foreach(在mc中匹配m)
{
开关(m值)
{
案例“[TestMode]”:
strTextToReplace=strTextToReplace.Replace(m.Value,“--新测试模式--”);
打破
案例“[RefDUT]”:
strTextToReplace=strTextToReplace.Replace(m.Value,“--New Ref DUT-->”);
打破
//在此处添加其他案例陈述
违约:
打破
}
}
非常感谢:P哦,是的,我的情况是只有几行HTML,这样我的生活更轻松!