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"
代碼:
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; } } }
實例代碼:
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文件,只需界說以下模板:
<?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的WordStr辦法則每次都要去剖析字符串,並且假如標記值中含有標記,會影響生成的頁面。
2、模板可以從文件讀入,是以模板文件可使用各類網頁制造對象編纂。
願望本文所述對年夜家C#法式設計有所贊助。