服务器之家

服务器之家 > 正文

C#实现动态生成静态页面的类详解

时间:2021-11-18 11:49     来源/作者:且行且思

本文实例讲述了C#实现动态生成静态页面的类。分享给大家供大家参考,具体如下:

动态生成静态页面有许多好处,比如生成html网页有利于被搜索引擎收录。同时,由于减少了数据访问,减轻对数据库访问的压力,提高了网页打开速度。

基本思路:

使用一个字符串作为页面模板,再页面中包含用若干标志(用 {标志名} 表示),生成页面时,将标志替换为对应的值。

实现方法:

在初始化TextTemplate实例时读入模板,以标志为分割点将模板分割成几部分,生成页面时只需简单的将模板内容和标志的值连接起来。例如:
假如有一个模板 ABCD{TAG1}EFG{TAG2}HIJ{TAG3}KMUN
初始化时将模板分割成 "ABCD","EFG","HIJ","KMUN"四个字符串,
假设TAG1=“123”,TAG2=“456”,TAG3=“789”
则生成是相当于执行"ABCD"+"123"+"EFG"+"456"+"HIJ"+"789"+"KMUN"

代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.IO;
/// <summary>
/// 表示一个文本模板,该类使用一个字符串作为模板,通过将模板中的标志替换为对应的值(模板中的标志用 {标志名} 表示)生成新的文本
/// </summary>
/// <example>以下代码用文本模板生成IMG标志
/// <code>
/// static class Program
/// {
///  [STAThread]
///  static void Main()
///  {
///   TextTemplate temp = new TextTemplate("&lt;img src='{src}' id="codetool">

实例代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
static class Program
{
 [STAThread]
 static void Main()
 {
  TextTemplate temp = new TextTemplate("<img src='{src}' id="codetool">

输出为:

<img src='pic.bmp' xml" id="highlighter_765033">

?
1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
 <appSettings></appSettings>
 <connectionStrings>
  <add
   name="DJDB.LocalSqlServer"
   connectionString="{CONNECTIONSTRING}"
   providerName="System.Data.SqlClient"
  />
 </connectionStrings>
 其他配置
</configuration>

在设置标志 CONNECTIONSTRING 的值即可,这种方法比用XMLDocument类要方便得多。

总结:

TextTemplate的优点有:

1、模板只在初始化时就分析并分割存储,当使用同一模板生成多个页面时,只是简单的件模板内容和标志的值连接起来,不需要每次都去分析模板,如果使用string的Replace方法则每一次都要去分析字符串,而且如果标志值中含有标志,会影响生成的页面。

2、模板可以从文件读入,因此模板文件可以使用各种网页制作工具编辑。

希望本文所述对大家C#程序设计有所帮助。

相关文章

热门资讯

返回顶部