陋室铭
永远也不要停下学习的脚步(大道至简至易)

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Xml;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;


namespace AspNet
{
    /// <summary>
    /// 遍历指定文件夹下所有的Data.xml文件并动态生成HTML静态页面!
    /// 运行过程:[1调用2,2调用3,3调用4]
    /// </summary>
    public class GetPageHtml : System.Web.UI.Page
    {
        protected System.Web.UI.WebControls.Button WebClientButton;
        protected System.Web.UI.WebControls.TextBox ContentHtml;
        protected System.Web.UI.WebControls.Button GetText;
        protected System.Web.UI.WebControls.TextBox UrlText;
        protected System.Web.UI.WebControls.Button Button2;
        protected System.Web.UI.HtmlControls.HtmlInputFile FilePath;
        private string PageUrl = "";

        private void Page_Load(object sender, System.EventArgs e)
        {
        }

        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        /// 设计器支持所需的方法 - 不要使用代码编辑器修改
        /// 此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {   
            this.WebClientButton.Click += new System.EventHandler(this.WebClientButton_Click);
            this.Button2.Click += new System.EventHandler(this.Button2_Click);
            this.Load += new System.EventHandler(this.Page_Load);

        }
        #endregion

        /// <summary>
        /// 获取HTML代码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void WebClientButton_Click(object sender, System.EventArgs e)
        {
 
            PageUrl = UrlText.Text.Trim();
            WebClient wc = new WebClient();
            wc.Credentials = CredentialCache.DefaultCredentials;
           
            Byte[] pageData = wc.DownloadData(PageUrl);
            ContentHtml.Text = Encoding.Default.GetString(pageData);    
            wc.Dispose(); 
        }


 
        /// <summary>
        /// 方法1:调用方法2 BianLi 去遍历文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button2_Click(object sender, System.EventArgs e)
        {
                       
            string Dir=FilePath.Value.Trim();
            string str="";

            if (Dir=="")
            {
                Response.Write("<script>alert('请选择要生成页面的文件夹好不好,老大!')</script>");
                return;
            }
            else
            {            

                //Response.Write(Dir.Replace(Dir.Remove(0,Dir.LastIndexOf(@"\")),"")+@"\");
                str=Dir.Replace(Dir.Remove(0,Dir.LastIndexOf(@"\")),"")+@"\";
                //调用遍历文件夹的方法BianLi(path)
                BianLi(str);
                Response.Write("<script>alert('所有HTML静态页面已经生成完毕!')</script>"); 
            }

        }
        /// <summary>
        /// 方法2:遍历出指定文件夹下的所有文件,并调用方法3:ReadXmlData(Dir)读取XML数据
        /// </summary>
        /// <param name="path"></param>
        private void BianLi(string path)
        {
            string[] fileNames = Directory.GetFiles(path);
            string[] directories = Directory.GetDirectories(path);
            string Dir="";

            foreach (string file in fileNames)
            {
                     //如果路径信息中包含Data.xml文件则输出有用的路径
                     if(file.Remove(0,file.LastIndexOf(@"\")).Replace(@"\","")=="Data.xml")   
                     
                        Dir=file.Remove(0,file.IndexOf(@"car\")).Replace("Data.xml","").Replace(@"\GetPageHtml\","").Replace(@"\",@"/").Trim();

                      //调用ReadXmlData方法去读取Data.xml信息^_^
                      if(Dir!="")  ReadXmlData(Dir);
                      //Response.Write(Dir+"<br>");    
                     
            }

            foreach (string dir in directories)
            {
                //再次遍历
                BianLi(dir);

            }
        }

         
        /// <summary>
        /// 方法3:ReadXmlData,读取xml信息,调用方法4去生成HTML页面
        /// </summary>
        private void ReadXmlData(string filepath)
        {
            string FileName = Server.MapPath(@filepath+"Data.xml");

            if ( ! System.IO.File.Exists(FileName))
            {
                // 输出文件不存在错误信息
                Response.Write("抱歉,Data.xml文件不存在");
                return;
            }
  
            XmlDocument doc = new XmlDocument();

            try
            {

                doc.Load(FileName);   
                //输出指定的一个结点:
                //XmlNode node = doc.SelectSingleNode("//main[@id='1']");
                //输出所有的结点^_^
                XmlNode node = doc.SelectSingleNode("//Root");
                if (node != null)
                { 
                    int i=0;
                    int j=1;
                    string str="";
                    foreach (XmlElement E in node.ChildNodes)
                    {
                        foreach (XmlElement F in E.ChildNodes)
                        {
                      
                            //先用_组合字符
                            str=str+F.OuterXml+"_"; 
                            str=str.Trim();
                            i=i+1;
                            if(i %  3==0)
                            {
                                                       
                                string delimStr = "_";
                                char [] delimiter = delimStr.ToCharArray();
                                string [] split =str.Split(delimiter);                           
                                //利用撤分的变量来调用生成静态页面的方法:
                                CreateHtml(j,split[0],split[1],split[2],@filepath);
        if (i==1) Response.Write(@filepath+"<br>");
                                str="";                                
                                j=j+1;
                       
                            }

                        }    
                    }
              
                }
            }

            catch
            {
                // 输出错误信息:xml格式不正确
               // Response.Write("Data.xml格式不正确");
               // Response.Write("错误文件路径信息:"+@filepath+"<br>");
                return;
            }

                     
        }


             
        /// <summary>
        ///  方法4:CreateHtml,根据读取的xml信息循环生成HTM静态页面
        /// </summary>
        /// <param name="id"></param>
        /// <param name="Car_Jpg"></param>
        /// <param name="Car_Title"></param>
        /// <param name="Car_Content"></param>
        private void CreateHtml(int id,string Car_Jpg,string Car_Title,string Car_Content,string filepath )
        {
            //定义HTML模板
            string content = ContentHtml.Text;  
            //定义生成的HTM文件名
            string FileName = @filepath+id + ".htm";

            //判断ID.HTM是否存在^_^,存在立即删除
            if (File.Exists(Server.MapPath(".") + Path.DirectorySeparatorChar +FileName))           
                File.Delete(Server.MapPath(".") + Path.DirectorySeparatorChar +FileName);

            FileStream fs = new FileStream(Server.MapPath(".") + Path.DirectorySeparatorChar + FileName, FileMode.CreateNew, FileAccess.Write, FileShare.None);
            StreamWriter sr = new StreamWriter(fs,System.Text.Encoding.GetEncoding("Gb2312"));           
         
            //替换图片
            content = content.Replace("Car_Jpg",Car_Jpg);
            //替换标题
            content = content.Replace("Car_Title",Car_Title);
            //替换内容
            content = content.Replace("Car_Content",Car_Content);
            //替换内容
            content = content.Replace("Car_ID",id.ToString());
            //替换HTM代码中的多余字符:<sub></sub>
            content = content.Replace("<sub>","");
            content = content.Replace("</sub>","");
           
            //到这里才生成HTML静态页面^_^,不过挺舒服的拉^_^
            sr.WriteLine(content);
            sr.Close();
            sr = null;
     
        }

       
              
    }


  }

+++++++++++++++++++++++++Data.xml
<?xml version="1.0" encoding="GB2312" ?>
<Root>
<main>
<sub>1.jpg</sub>
<sub>title</sub>
<sub>content</sub>
</main>

<main>
<sub>2.jpg</sub>
<sub>title</sub>
<sub>content</sub>
</main>
</Root>

posted on 2006-12-30 12:44  宏宇  阅读(581)  评论(0编辑  收藏  举报