思路二:若用硬編碼方式,工作量極大,需非常多 HTML 程式碼。除錯困難。且硬編碼產生 HTML 樣式無法修改,若網站更換樣式,必須重新編碼,給後期帶來巨大工作量。
因此這裡採用第一種思路。
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<body >
<table $htmlformat[0] height="100%" border="0" width="100%" cellpadding="10" cellspacing="0" bgcolor="#eeeeee" style="border:1px solid #000000">
<tr>
<td width="100%" valign="middle" align="left">
<span style="color: $htmlformat[1];font-size: $htmlformat[2]">$htmlformat[3]</span>
</td>
</tr>
</table>
</body>
</html>
//---------------------讀 HTML 模板頁面到 StringBuilder 物件裡----
string[] format=new string[4];//定義與 HTML 標記數目一致陣列
StringBuilder htmltext=new StringBuilder();
try
{
using (StreamReader sr = new StreamReader("存放模板頁面路徑與頁面名"))
{
String line;
while ((line = sr.ReadLine()) != null)
{
htmltext.Append(line);
}
sr.Close();
}
}
catch
{
Response.Write("<Script>alert('讀取檔案錯誤')</Script>");
}
//---------------------給標記陣列賦值------------
format[0]="background=\"bg.jpg\"";//背景圖片
format[1]= "#990099";//字型顏色
format[2]="150px";//字型大小
format[3]= "<marquee>產生的模板html頁面</marquee>";//文字說明
//----------替換 HTML 裡標記為你想加內容
for(int i=0;i<4;i++)
{
htmltext.Replace("$htmlformat["+i+"]",format[i]);
}
//----------產生 HTML 檔案------------------――
try
{
using(StreamWriter sw=new StreamWriter("存放路徑與頁面名",false,System.Text.Encoding.GetEncoding("GB2312")))
{
sw.WriteLine(htmltext);
sw.Flush();
sw.Close();
}
}
catch
{
Response.Write ("The file could not be wirte:");
}
用此方法可方便產生 HTML 檔案。程式使用迴圈替換,因此對需替換大量元素模板速度非常快。