asp.net类序列化生成xml文件实例详解(2)

#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 + "https://www.jb51.net/" + 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=https://www.jb51.net/"utf-16/"", "encoding=https://www.jb51.net/"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

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjwjxx.html