gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 12:53:17 24 4
gpt4 key购买 nike

在我的 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;
}
}

关于c# - 使用 C# 编辑 HTML 并替换其中的某些文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5817118/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com