In my C# WinForms program I want to generate a report as HTML. What I am doing now is using StringBuilder and TextWriter and write all html codes and save the file as HTML. It is working but I want to enhance the workflow.
So my idea is having a HTML template with certain texts that are going to be replaced by a special tag or something (I have worked with Smarty template before, so I mean something like that).
Imagine the HTML code below:
<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>
So basically what I want to do is replace a text between [] in the above html with certain strings that has been produced in my C# program.
Any ideas, code snippets, links to tuturial and etc... will be appriciated!
There is so much danger parsing HTML with regex or quick and dirty replaces. So many things can go wrong if the HTML has been properly "prepared" (which is a diffcult thing to do with 100% certainty.) The HTML Agility Pack mentioned in Milde's answer is a great way to go but it might feel like using a sledgehammer to crack open a nut.
However, if you are confident of the HTML that will be parsed, then the following should be able to get you going quickly:
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With