Iterate through all the XML files under the specified folder and dynamically generate HTML pages!

Source: Internet
Author: User
Tags foreach format define object return string split trim
xml| Traversal | dynamic | Generate html| page

Function: Iterate through all the XML files under the specified folder and generate HTML pages dynamically!
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
   /// Iterate through all the Data.xml files under the specified folder and dynamically generate HTML static pages!
   ///Run procedure: [1 call 2,2 call 3,3 call 4]
    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);

Designer supports required methods-do not use the Code editor to modify
The contents of this method.
private void InitializeComponent ()
This. + = new System.EventHandler (this. Webclientbutton_click);
This. + = new System.EventHandler (this. button2_click);
This. Load + = new System.EventHandler (this. Page_Load);


       / Get HTML code
        ///<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 (); 

        ///Method 1: Invoke Method 2 Bianli to traverse the file
       ///<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" Please select the folder where you want to generate the page okay, Boss! ') </script> ");

               //response.write ( Dir.replace (Dir.remove (0,dir.lastindexof (@)), "") +@ "\");
                Str=dir.replace ( Dir.remove (0,dir.lastindexof (@)), "" "+@" \ ";
               // Calling methods to traverse a folder Bianli (path)
                 Bianli (str);
                Response.Write (" <script>alert (' All HTML static pages have been generated! ') </script> ");

        Method 2: Iterate through all the files under the specified folder and call method 3:readxmldata (Dir) to read the XML data
       ///</ 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)
                     //If the path information contains data.xml files, output a useful path
                      if (file. Remove (0,file. LastIndexOf (@ "\")). Replace (@ "\", "") = = "Data.xml")   
                         Dir=file. Remove (0,file. IndexOf (@ "car\")). Replace ("Data.xml", ""). Replace (@ "\getpagehtml\", ""). Replace (@ "\", @ "/"). Trim ();

                      //Call Readxmldata method to read data.xml information '
                       if (dir!= "")   Readxmldata (Dir );
                      //response.write (dir+ "<br>");    

foreach (String dir in directories)
Traverse again
Bianli (dir);


       ///< Summary>
       ///method 3:readxmldata, reading XML information, calling method 4 to generate HTML pages
        Private void Readxmldata (string filepath)
             string FileName = Server.MapPath (@filepath + "Data.xml");

if (! System.IO.File.Exists (FileName))
No error message exists for output file
Response.Write ("Sorry, data.xml file does not exist");

XmlDocument doc = new XmlDocument ();


Doc.   Load (FileName);

//output a specified node:

//xmlnode node = doc. selectSingleNode ("//main[@id = ' 1 ']");

//Output all nodes '

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)



///First Use _ Combination character

str=str+f.outerxml+ "_";

Str=str. Trim ();


if (i% 3==0)



String Delimstr = "_";

Char [] delimiter = Delimstr.tochararray ();

string [] split =str.                            Split (delimiter);

Use a split variable to invoke a method that generates a static page:

createhtml (j,split[0],split[1],split[2], @filepath);

if (i==1) Response.Write (@filepath + "&lt;br&gt;");

str= "";





Output error message: XML is not in the correct format
Response.Write ("Data.xml format is not correct");
Response.Write ("Error file path information:" + @filepath + "<br>");


       ///  Method 4: Createhtml, the HTM static page is generated from the read XML information
        ///<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)
            //define HTML templates
            string content = contenthtml.text;  
            //Define the generated HTM file name
             string FileName = @filepath +id + ". htm";

Determine if id.htm exists ', exist immediately delete
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.cre Atenew, FileAccess.Write, Fileshare.none);

StreamWriter sr = new StreamWriter (fs,system.text.encoding.getencoding ("Gb2312"));

//Replace picture

content = content. Replace ("Car_jpg", car_jpg);

//Replace title

content = content. Replace ("Car_title", car_title);

//replacement content

content = content. Replace ("Car_content", car_content);

//replacement content

content = content. Replace ("car_id", ID. ToString ());

Replace the extra characters in the HTM code:&lt;sub&gt;&lt;/sub&gt;

content = content. Replace ("&lt;sub&gt;", "");

content = content. Replace ("&lt;/sub&gt;", "");


//Here to generate HTML static page ', but quite comfortable pull '

Sr. WriteLine (content);

Sr. Close ();

sr = null;





<?xml version= "1.0" encoding= "GB2312"?>


Related Article

Alibaba Cloud 10 Year Anniversary

With You, We are Shaping a Digital World, 2009-2019

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.