程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> C#實現動態生成靜態頁面的類詳解

C#實現動態生成靜態頁面的類詳解

編輯:關於C語言

本文實例講述了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("<img src='{src}' alt='{alt}' />"); /// Console.WriteLine(temp.Render("pic.bmp","Image")); /// Hashtable values = new Hashtable(); /// values.Add("src", "pic.bmp"); /// values.Add("alt", "image"); /// Console.WriteLine(temp.Render(values)); /// } /// } /// /// 輸出為: /// <img src='pic.bmp' alt='Image' /> /// <img src='pic.bmp' alt='image' /> /// /// </code> /// </example> public class TextTemplate { TextTemplateTag[] _tags; String[] _contentParts; int _tagCount; private TextTemplate() { _tagCount = 0; _tags = null; _contentParts = null; } /// <summary> /// 用指定的模板初始化TextTemplate /// </summary> /// <param name="content">模板內容</param> public TextTemplate(String content) { FromString(content); } /// <summary> /// 用指定的模板初始化TextTemplate,模板內容重文件讀入 /// </summary> /// <param name="file">模板文件位置</param> /// <param name="encoding">文件使用的編碼</param> public TextTemplate(string file, Encoding encoding) { StreamReader sr = new StreamReader(file, encoding); try { string content = sr.ReadToEnd(); FromString(content); } catch (Exception) { sr.Close(); throw; } sr.Close(); } /// <summary> /// 讀入模板並以標志為分割點分割模板 /// </summary> /// <param name="content"></param> private void FromString(String content) { MatchCollection mc = Regex.Matches(content, "{\\w+}"); _tagCount = mc.Count; _tags = new TextTemplateTag[mc.Count]; _contentParts = new string[mc.Count + 1]; int index = 0; foreach (Match m in mc) { _tags[index++] = new TextTemplateTag(m.Value.Substring(1, m.Value.Length - 2), m.Index, m.Length); } int start = 0; index = 0; foreach (TextTemplateTag con in _tags) { _contentParts[index] = content.Substring(start, con.Position - start); start = con.Position + con.Length; index++; } if (start < content.Length) _contentParts[index] = content.Substring(start); } /// <summary> /// 用指定的值生成文本 /// </summary> /// <param name="values">各標志對應的值(用標志名作為key)</param> /// <returns>生成的文本</returns> /// <example>以下代碼用文本模板生成IMG標志 /// <code> /// static class Program /// { /// [STAThread] /// static void Main() /// { /// TextTemplate temp = new TextTemplate("<img src='{src}' alt='{alt}' />"); /// Console.WriteLine(temp.Render("pic.bmp","Image")); /// Hashtable values = new Hashtable(); /// values.Add("src", "pic.bmp"); /// values.Add("alt", "image"); /// Console.WriteLine(temp.Render(values)); /// } /// } /// /// 輸出為: /// <img src='pic.bmp' alt='Image' /> /// <img src='pic.bmp' alt='image' /> /// /// </code> /// </example> public string Render(Hashtable values) { StringBuilder result = new StringBuilder(8 * 1024); int i = 0; for (i = 0; i < _tagCount; i++) { result.Append(_contentParts[i]); if (values[_tags[i].Name] != null) result.Append(values[_tags[i].Name]); else result.Append("{" + _tags[i].Name + "}"); } result.Append(_contentParts[i]); return result.ToString(); } /// <summary> /// 用指定的值生成文本 /// </summary> /// <param name="args">各標志對應的值(忽略標志名,第一個標志對應第一個參數,以此類推)</param> /// <returns>生成的文本</returns> /// <example>以下代碼用文本模板生成IMG標志 /// <code> /// static class Program /// { /// [STAThread] /// static void Main() /// { /// TextTemplate temp = new TextTemplate("<img src='{src}' alt='{alt}' />"); /// Console.WriteLine(temp.Render("pic.bmp","Image")); /// Hashtable values = new Hashtable(); /// values.Add("src", "pic.bmp"); /// values.Add("alt", "image"); /// Console.WriteLine(temp.Render(values)); /// } /// } /// /// 輸出為: /// <img src='pic.bmp' alt='Image' /> /// <img src='pic.bmp' alt='image' /> /// /// </code> /// </example> public string Render(params object[] args) { StringBuilder result = new StringBuilder(2 * 1024); int i = 0; for (i = 0; i < _tagCount; i++) { result.Append(_contentParts[i]); result.Append(args[i].ToString()); } result.Append(_contentParts[i]); return result.ToString(); } /// <summary> /// 用指定的值生成文本,並保存到文件中 /// </summary> /// <param name="file">要保存的文件路徑</param> /// <param name="encoding">文件的編碼</param> /// <param name="values">各標志對應的值(用標志名作為key)</param> public void SaveAs(string file, Encoding encoding, Hashtable values) { StreamWriter sw = new StreamWriter(file, false, encoding); try { String content = Render(values); sw.Write(content); } catch (Exception) { sw.Close(); throw; } sw.Close(); } /// <summary> /// 用指定的值生成文本,並保存到文件中 /// </summary> /// <param name="file">要保存的文件路徑</param> /// <param name="encoding">文件的編碼</param> /// <param name="args">各標志對應的值(忽略標志名,第一個標志對應第一個參數,以此類推)</param> public void SaveAs(string file, Encoding encoding, params object[] args) { StreamWriter sw = new StreamWriter(file, false, encoding); try { String content = Render(args); sw.Write(content); } catch (Exception) { sw.Close(); throw; } sw.Close(); } /// <summary> /// 將模板以指定的分隔標志分隔成小模板 /// </summary> /// <param name="splitTag"></param> /// <returns></returns> public TextTemplate[] Split(string splitTag) { List<TextTemplate> temps = new List<TextTemplate>(); List<string> contentParts = new List<string>(); List<TextTemplateTag> tags = new List<TextTemplateTag>(); int i = 0; foreach (string content in _contentParts) { contentParts.Add(content); if (i >= _tags.Length || _tags[i].Name == splitTag) { TextTemplate newTemp = new TextTemplate(); newTemp._contentParts = contentParts.ToArray(); newTemp._tags = tags.ToArray(); newTemp._tagCount = tags.Count; temps.Add(newTemp); contentParts.Clear(); tags.Clear(); } else tags.Add(new TextTemplateTag(_tags[i].Name, _tags[i].Position, _tags[i].Length)); i++; } return temps.ToArray(); } } internal class TextTemplateTag { int _position, _length; string _name; public TextTemplateTag(string name, int pos, int len) { _name = name; _position = pos; _length = len; } public string Name { get { return _name; } } public int Position { get { return _position; } } public int Length { get { return _length; } } }

實例代碼:

? 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}' alt='{alt}' />"); Console.WriteLine(temp.Render("pic.bmp","Image")); Hashtable values = new Hashtable(); values.Add("src", "pic.bmp"); values.Add("alt", "image"); Console.WriteLine(temp.Render(values)); } }

輸出為:

<img src='pic.bmp' alt='Image' />
< img src='pic.bmp' alt='image' />

其他應用:

TextTemplate還可以用來在安裝網站時生成Web.Config文件,只需定義以下模板:

? 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、模板可以從文件讀入,因此模板文件可以使用各種網頁制作工具編輯。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved