我正在从c#应用程序生成动态HTML,通过使用字符串构建器,附加html标记并最终形成完整的html.在所有的stringbuilder中,我用c#object替换html占位符.
正在构建的html是复杂的,我需要从c#属性填充占位符,有时需要填充数据库调用.没有XML所以不使用XSLT.由于我的html文件庞大而且需要很多字符串buider.大多数部分都是根据业务逻辑重复的.
现在一切都工作正常,我想从stringbuilder中删除带有硬编码的html字符串,因为后来的维护很难.任何最好的建议,从控制台应用程序摆脱硬编码的HTML.
性能方面,使用大量的字符串构建器是好的(至少使用500个字符串构建器)例如,我的html拆分如下
我刚刚提供了几行代码供您参考.
代码示例:
htmlStringBuilder.Append("<table class=\"paddingIndendation\" style=\"width: 100%;\" border=\"1\">");
htmlStringBuilder.Append(string.Format("<tr><td>Location {0}</td><td>:</td><td>{1}</td></tr>", location.LocationNumber, location.AddressLine1));
htmlStringBuilder.Append(string.Format("<tr><td colspan=\"2\" style=\"text-align:right;\"></td><td>{0}</td></tr>", location.AddressLine2));
htmlStringBuilder.Append(string.Format("<tr><td colspan=\"2\" style=\"text-align:right;\"></td><td>{0} {1}</td></tr>", location.PostalCode, location.City));
htmlStringBuilder.Append(string.Format("<tr><td colspan=\"2\" style=\"text-align:right;\"></td><td>{0} {1}</td></tr>", this.Id,this.StartEffectiveDate));
Run Code Online (Sandbox Code Playgroud)
我想将hardcorded html内容移动到某处(可能是文件或资源文件)并用属性替换占位符.任何人都可以建议最好的方法来做到这一点.
如果你看一下Maintainence,你可以用这样的占位符来制作HTML文件
<table class="paddingIndendation" style="width: 100%;" border="1">
<tr>
<td>Location ~LocationNumber~</td>
<td>:</td>
<td>~AddressLine1~</td>
</tr>
<tr>
<td colspan="2" style="text-align:right;"></td>
<td>~AddressLine2~</td>
</tr>
<tr>
<td colspan="2" style="text-align:right;"></td>
<td>~PostalCode~ ~City~</td>
</tr>
Run Code Online (Sandbox Code Playgroud)
将字符串加载到字符串变量中
string htmlstring = File.ReadAllText("yourhtml.txt");
Run Code Online (Sandbox Code Playgroud)
然后可能你可以创建一个小函数,你可以用这样的任何属性或数据库调用替换所有这些占位符
htmlstring = htmlstring.Replace("~LocationNumber~",location.LocationNumber);
htmlstring = htmlstring.Replace("~AddressLine1~",location.AddressLine1);
htmlstring = htmlstring.Replace("~AddressLine2~",location.AddressLine2);
htmlstring = htmlstring.Replace("~PostalCode~",location.PostalCode);
htmlstring = htmlstring.Replace("~City~",location.City);
Run Code Online (Sandbox Code Playgroud)