asp.net類序列化產生xml檔案執行個體詳解_實用技巧

來源:互聯網
上載者:User

本文執行個體講述了asp.net類序列化產生xml檔案的方法。分享給大家供大家參考,具體如下:

根據設計的需求需要開發多個商品的API 原XML檔案如下:

<urlset> <url>  <loc>http://www.xxxxx.com/todaydetials.aspx?id=143</loc>  <data>   <display>    <website>愛購114</website>    <siteurl>http://www.xxxxx.com/</siteurl>    <city>杭州</city>    <webSitetitle></webSitetitle>    <image></image>    <startTime>2011-2-9</startTime>    <endTime>2011-2-15</endTime>    <value>3880</value>    <price>2088</price>    <rebate>0.53</rebate>    <bought>0</bought>   </display>   </data> </url></urlset>

現在需求是要根據資料庫有幾條商品資訊 相應的API XML檔案出現幾個URL節點! 採用類序列化成XML檔案然後讀取相應產生的XML檔案就可以展示多個商品XML的資訊 實現代碼如下:

首先定義好XML 各個節點的資料及父子節點的關係類:

#region 定義資料實體類xml資料結構public class urlset{  public List<url> urlList  {   get;   set;  }}public class url{  public string loc  {   get;   set;  }  public List<data> dataList  {   get;   set;  }}public class data{  public List<display> displayList  {   get;   set;  }}public class display{  public string website  {   get;   set;  }  public string siteurl  {   get;   set;  }  public string city  {   get;   set;  }  public string webSitetitle  {   get;   set;  }  public string image  {   get;   set;  }  public string startTime  {   get;   set;  }  public string endTime  {   get;   set;  }  public double value  {   get;   set;  }  public double price  {   get;   set;  }  public double rebate  {   get;   set;  }  public int bought  {   get;   set;  }}#endregion

第二步:#region 定義擷取網站資訊實體類

public class WebSiteInfo{  /// <summary>  /// 商品標題  /// </summary>  public string title { get; set; }  /// <summary>  /// 商品發布時間  /// </summary>  public DateTime createtime { get; set; }  /// <summary>  /// 商品圖片  /// </summary>  public string productimg { get; set; }  /// <summary>  /// 市場價  /// </summary>  public decimal market_price { get; set; }  /// <summary>  /// 團購價  /// </summary>  public decimal team_price { get; set; }  /// <summary>  /// 折扣價  /// </summary>  public decimal zhekou_price { get; set; }  /// <summary>  /// 城市名稱   /// </summary>  public string cityName { get; set; }  /// <summary>  /// 商品開始時間  /// </summary>  public DateTime begin_time { get; set; }  /// <summary>  /// 結束時間  /// </summary>  public DateTime end_time { get; set; }  /// <summary>  /// 商家名稱  /// </summary>  public string merchants_id { get; set; }  /// <summary>  /// 本單詳情  /// </summary>  public string description { get; set; }  /// <summary>  /// 最低購買人數  /// </summary>  public int lowBuNo { get; set; }  /// <summary>  /// 商家地址  /// </summary>  public string Address { get; set; }  /// <summary>  /// 商家電話  /// </summary>  public string Telphone { get; set; }  /// <summary>  /// 城市區號  /// </summary>  public string cCode { get; set; }  /// <summary>  /// 檔案夾名稱  /// </summary>  public string folderName { get; set; }  /// <summary>  /// 團購狀態   /// </summary>  public string StatusMessage { get; set; }  /// <summary>  /// 現在購買人數  /// </summary>  public int nownumber { get; set; }  /// <summary>  /// 商品編號  /// </summary>  public int productID { get; set; }}#endregion

第三步:擷取資料庫商品資訊記錄並添加到對象的集合中(Arraylist):

#region 擷取xml實體類資訊/// <summary>/// 擷取xml實體類資訊/// </summary>/// <returns></returns>public static ArrayList GetWebModelInfo(){  ArrayList list = new ArrayList();  string strSQL = "select a.id, a.merchantsID,a.cCode,a.prodCode,a.statue,a.now_number, a.title,a.createtime,a.productimg,a.market_price,a.team_price,a.zhekou_price,a.cityName,a.begin_time,a.end_time,a.description,a.lowBuyNo,b.Address,b.Tel from tg_product as a left join tg_merchants as b on a.merchantsID=b.merchants_id where a.ispublic=1 and statue>-1 and getdate()<dateadd(day,1,a.end_time) order by a.createtime desc";  DataSet ds = FrameWork.Data.SqlHelper.ReturnDataSet(CommandType.Text, strSQL, null);  if (ds.Tables[0].Rows.Count > 0)  {   foreach (DataRow dr in ds.Tables[0].Rows)   {    WebSiteInfo webModel = new WebSiteInfo();    //城市名稱    webModel.cityName = dr["cityName"].ToString();    //商品標題    webModel.title = dr["title"].ToString();    //商品建立時間    webModel.createtime = Convert.ToDateTime(dr["createtime"].ToString());    //商家名稱    webModel.merchants_id = dr["merchantsID"].ToString();    //商品圖片    webModel.productimg = dr["productimg"].ToString();    //市場價    webModel.market_price = Convert.ToDecimal(dr["market_price"].ToString());    //團購價    webModel.team_price = Convert.ToDecimal(dr["team_price"].ToString());    //折扣價    webModel.zhekou_price = Convert.ToDecimal(dr["zhekou_price"].ToString());    //開始時間    webModel.begin_time = Convert.ToDateTime(dr["begin_time"].ToString());    //結束時間    webModel.end_time = Convert.ToDateTime(dr["end_time"].ToString());    //商品說明    webModel.description = dr["description"].ToString();    //最低購買數量    webModel.lowBuNo = Convert.ToInt32(dr["lowBuyNo"].ToString());    //商家電話    webModel.Telphone = dr["Tel"].ToString();    //商家地址    webModel.Address = dr["Address"].ToString();    //城市編號    webModel.cCode = dr["cCode"].ToString();    //圖片檔案夾名稱    webModel.folderName = dr["prodCode"].ToString();    //現在購買人數    webModel.nownumber = Convert.ToInt32(dr["now_number"].ToString());    //商品編號    webModel.productID = Convert.ToInt32(dr["id"].ToString());    int status = Convert.ToInt32(dr["statue"].ToString());    switch (status)    {     case 0:      webModel.StatusMessage = "結束";      break;     case 1:      webModel.StatusMessage = "成功";      break;    }    list.Add(webModel);   }  }   return list;}#endregion

最後一步將資料庫讀取來的資訊賦值到XML 資料類型中 並序列化成XML檔案儲存成XML格式的檔案讀取檔案展現到介面:

#region 頁面載入 根據資料庫商品記錄數產生xml檔案資訊/// <summary>/// 頁面載入 根據資料庫商品記錄數產生xml檔案資訊/// </summary>List<url> urlList = null;urlset urlsetList = new urlset();protected void Page_Load(object sender, EventArgs e){  if (!Page.IsPostBack)  {    ArrayList listinfo=GetWebModelInfo();    urlList = new List<url>();   for (int i = 0; i < listinfo.Count; i++)   {    WebSiteInfo webInfo = listinfo[i] as WebSiteInfo;    List<display> displayList = new List<display>();    display display = new display();    display.website = "愛購114";    display.siteurl = "http://www.xxxxx.com/";    //城市名稱    display.city = webInfo.cityName;    //商品標題    display.webSitetitle = webInfo.title;    //商品圖片    display.image = "http://211.155.235.30/tuangou/" + webInfo.folderName + "/" + webInfo.productimg;    //商品開始時間    display.startTime = webInfo.begin_time.ToShortDateString();    //商品結束時間    display.endTime = webInfo.end_time.ToShortDateString();    //市場價    display.value = Convert.ToDouble(webInfo.market_price);    //團購價    display.price = Convert.ToDouble(webInfo.team_price);    //折扣價    display.rebate = Convert.ToDouble(webInfo.zhekou_price);    //現在購買的人數    display.bought = webInfo.nownumber;    displayList.Add(display);    List<data> dataList = new List<data>();    data data = new data();    data.displayList = displayList;    dataList.Add(data);    url url = new url();    url.loc = String.Format("http://www.xxxxx.com/todaydetials.aspx?id={0}", webInfo.productID.ToString());    url.dataList = dataList;    urlList.Add(url);    urlsetList.urlList = urlList;   }   try   {    XmlSerializerNamespaces xmlns = new XmlSerializerNamespaces();    xmlns.Add(String.Empty, String.Empty);    //構造字串    StringBuilder sb = new StringBuilder();    //將字串寫入到stringWriter對象中    StringWriter sw = new StringWriter(sb);    //xml序列化對象 typeof(類名)    XmlSerializer ser = new XmlSerializer(typeof(urlset));    //把Stream對象和urlset一起傳入,序列化出一個字串sb    ser.Serialize(sw, urlsetList, xmlns);    sw.Close();    string FILE_NAME = HttpContext.Current.Server.MapPath("API/54tuan.xml");    FileInfo fi = new FileInfo(FILE_NAME);    //如果檔案己經存在則刪除該檔案     if (fi.Exists)    {     if (fi.Attributes.ToString().IndexOf("ReadOnly") >= 0) {      fi.Attributes = FileAttributes.Normal;     }     File.Delete(fi.Name);    }    //建立檔案 並寫入字串    using (StreamWriter sWrite = File.CreateText(FILE_NAME))    {     sWrite.Write(sb.ToString().Replace("encoding=/"utf-16/"", "encoding=/"utf-8/"").Replace("<urlList>", "").Replace("</urlList>", "").Replace("<dataList>", "").Replace("</dataList>", "").Replace("<displayList>", "").Replace("<displayList>", "").Replace("</displayList>", ""));     sWrite.Close();    }    //輸出序列化後xml檔案    Response.ClearContent();    Response.ClearHeaders();    Response.ContentType = "application/xml";    Response.WriteFile(HttpContext.Current.Server.MapPath("API/54tuan.xml"));    Response.Flush();    Response.Close();   }   catch (Exception ex)   {    Response.Write(ex.Message);   }   finally   {   }   }}#endregion

希望本文所述對大家asp.net程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.