asp.net类序列化生成xml文件实例详解
本文实例讲述了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>
现在需求是要根据数据库有几条商品信息相应的APIXML文件出现几个URL节点!采用类序列化成XML文件然后读取相应生成的XML文件就可以展示多个商品XML的信息实现代码如下:
首先定义好XML各个节点的数据及父子节点的关系类:
#region定义数据实体类xml数据结构 publicclassurlset { publicList<url>urlList { get; set; } } publicclassurl { publicstringloc { get; set; } publicList<data>dataList { get; set; } } publicclassdata { publicList<display>displayList { get; set; } } publicclassdisplay { publicstringwebsite { get; set; } publicstringsiteurl { get; set; } publicstringcity { get; set; } publicstringwebSitetitle { get; set; } publicstringimage { get; set; } publicstringstartTime { get; set; } publicstringendTime { get; set; } publicdoublevalue { get; set; } publicdoubleprice { get; set; } publicdoublerebate { get; set; } publicintbought { get; set; } } #endregion
第二步:#region定义获取网站信息实体类
publicclassWebSiteInfo { ///<summary> ///商品标题 ///</summary> publicstringtitle{get;set;} ///<summary> ///商品发布时间 ///</summary> publicDateTimecreatetime{get;set;} ///<summary> ///商品图片 ///</summary> publicstringproductimg{get;set;} ///<summary> ///市场价 ///</summary> publicdecimalmarket_price{get;set;} ///<summary> ///团购价 ///</summary> publicdecimalteam_price{get;set;} ///<summary> ///折扣价 ///</summary> publicdecimalzhekou_price{get;set;} ///<summary> ///城市名称 ///</summary> publicstringcityName{get;set;} ///<summary> ///商品开始时间 ///</summary> publicDateTimebegin_time{get;set;} ///<summary> ///结束时间 ///</summary> publicDateTimeend_time{get;set;} ///<summary> ///商家名称 ///</summary> publicstringmerchants_id{get;set;} ///<summary> ///本单详情 ///</summary> publicstringdescription{get;set;} ///<summary> ///最低购买人数 ///</summary> publicintlowBuNo{get;set;} ///<summary> ///商家地址 ///</summary> publicstringAddress{get;set;} ///<summary> ///商家电话 ///</summary> publicstringTelphone{get;set;} ///<summary> ///城市区号 ///</summary> publicstringcCode{get;set;} ///<summary> ///文件夹名称 ///</summary> publicstringfolderName{get;set;} ///<summary> ///团购状态 ///</summary> publicstringStatusMessage{get;set;} ///<summary> ///现在购买人数 ///</summary> publicintnownumber{get;set;} ///<summary> ///商品编号 ///</summary> publicintproductID{get;set;} } #endregion
第三步:获取数据库商品信息记录并添加到对象的集合中(Arraylist):
#region获取xml实体类信息 ///<summary> ///获取xml实体类信息 ///</summary> ///<returns></returns> publicstaticArrayListGetWebModelInfo() { ArrayListlist=newArrayList(); stringstrSQL="selecta.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.Telfromtg_productasaleftjointg_merchantsasbona.merchantsID=b.merchants_idwherea.ispublic=1andstatue>-1andgetdate()<dateadd(day,1,a.end_time)orderbya.createtimedesc"; DataSetds=FrameWork.Data.SqlHelper.ReturnDataSet(CommandType.Text,strSQL,null); if(ds.Tables[0].Rows.Count>0) { foreach(DataRowdrinds.Tables[0].Rows) { WebSiteInfowebModel=newWebSiteInfo(); //城市名称 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()); intstatus=Convert.ToInt32(dr["statue"].ToString()); switch(status) { case0: webModel.StatusMessage="结束"; break; case1: webModel.StatusMessage="成功"; break; } list.Add(webModel); } } returnlist; } #endregion
最后一步将数据库读取来的信息赋值到XML数据类型中并序列化成XML文件保存成XML格式的文件读取文件展现到界面:
#region页面加载根据数据库商品记录数生成xml文件信息 ///<summary> ///页面加载根据数据库商品记录数生成xml文件信息 ///</summary> List<url>urlList=null; urlseturlsetList=newurlset(); protectedvoidPage_Load(objectsender,EventArgse) { if(!Page.IsPostBack) { ArrayListlistinfo=GetWebModelInfo(); urlList=newList<url>(); for(inti=0;i<listinfo.Count;i++) { WebSiteInfowebInfo=listinfo[i]asWebSiteInfo; List<display>displayList=newList<display>(); displaydisplay=newdisplay(); 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=newList<data>(); datadata=newdata(); data.displayList=displayList; dataList.Add(data); urlurl=newurl(); 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 { XmlSerializerNamespacesxmlns=newXmlSerializerNamespaces(); xmlns.Add(String.Empty,String.Empty); //构造字符串 StringBuildersb=newStringBuilder(); //将字符串写入到stringWriter对象中 StringWritersw=newStringWriter(sb); //xml序列化对象typeof(类名) XmlSerializerser=newXmlSerializer(typeof(urlset)); //把Stream对象和urlset一起传入,序列化出一个字符串sb ser.Serialize(sw,urlsetList,xmlns); sw.Close(); stringFILE_NAME=HttpContext.Current.Server.MapPath("API/54tuan.xml"); FileInfofi=newFileInfo(FILE_NAME); //如果文件己经存在则删除该文件 if(fi.Exists) { if(fi.Attributes.ToString().IndexOf("ReadOnly")>=0){ fi.Attributes=FileAttributes.Normal; } File.Delete(fi.Name); } //创建文件并写入字符串 using(StreamWritersWrite=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(Exceptionex) { Response.Write(ex.Message); } finally { } } } #endregion
希望本文所述对大家asp.net程序设计有所帮助。