自动生成网页的基本思路是这样的,你需要建立一个模版,在这个模版里你定义那些需要改变的变量,然后你通过文件流读取你定义的模版,把它转换成string,这个时候无论你定义的静态页面-html,或者动态页面-aspx-php-jsp,都无所谓,他们的源代码会被作为一个字符串读入,这个时候你需要replace替换一下那些在模版中定义的变量即可,然后保存。比如我最近做的是,要在视频添加后自动生成一个页面来播放这个视频。下面我把俩个主要的方法列下来,大家一看就明白,哦,我这个是在.net下写的。
public string WriteOldHtml(string strTemplePath, string strFilePath, string videopath)
{
Encoding code = Encoding.GetEncoding("gb2312");
string temp = strTemplePath;
// StreamReader sr = null;
StreamWriter sw = null;
string str = GetTemplet(strTemplePath); //通过流读取得到文件字符串
string htmlfilename = strFilePath + ".html";//存放网页地址
// 替换内容
// 这时,模板文件已经读入到名称为str的变量中了
str = str.Replace("videoName", videopath); //模板页中的ShowArticle
// 写文件
try
{
sw = new StreamWriter(htmlfilename, false, code);
sw.Write(str);
sw.Flush();
}
catch (Exception ex)
{
pd_fc.Show_Msg(ex.Message);
}
finally
{
sw.Close();
}
return htmlfilename;
}
public static string GetTemplet(string strTempletpath)
{
Encoding code = Encoding.GetEncoding("gb2312");
// 读取模板文件
string temp = strTempletpath;
StreamReader sr = null;
string str = "";
try
{
sr = new StreamReader(temp, code);
str = sr.ReadToEnd(); // 读取文件
}
catch (Exception exp)
{
sr.Close();
pd_fc.Show_Msg("请联系管理员");
}
return str;
}