asp. net class serialization to generate xml file instance details
- 2021-07-07 07:19:14
- OfStack
This article illustrates how to serialize the asp. net class to generate an xml file. Share it for your reference, as follows:
According to the design requirements, the original API XML files for developing multiple products are as follows:
<urlset>
<url>
<loc>http://www.xxxxx.com/todaydetials.aspx?id=143</loc>
<data>
<display>
<website> Love to buy 114</website>
<siteurl>http://www.xxxxx.com/</siteurl>
<city> Hangzhou </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>
Now the requirement is to have several URL nodes according to the corresponding API XML file with several commodity information in the database! Use class serialization into XML file and then read the corresponding generated XML file to show the information of multiple commodities XML. The implementation code is as follows:
First, define the data of each node of XML and the relationship class of parent and child nodes:
#region Defining Data Entity Classes xml Data structure
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
Step 2: # region Define Entity Class for Obtaining Web Site Information
public class WebSiteInfo
{
/// <summary>
/// Commodity title
/// </summary>
public string title { get; set; }
/// <summary>
/// Commodity release time
/// </summary>
public DateTime createtime { get; set; }
/// <summary>
/// Product picture
/// </summary>
public string productimg { get; set; }
/// <summary>
/// Market price
/// </summary>
public decimal market_price { get; set; }
/// <summary>
/// Group purchase price
/// </summary>
public decimal team_price { get; set; }
/// <summary>
/// Discounted price
/// </summary>
public decimal zhekou_price { get; set; }
/// <summary>
/// City name
/// </summary>
public string cityName { get; set; }
/// <summary>
/// Commodity start time
/// </summary>
public DateTime begin_time { get; set; }
/// <summary>
/// End time
/// </summary>
public DateTime end_time { get; set; }
/// <summary>
/// Merchant name
/// </summary>
public string merchants_id { get; set; }
/// <summary>
/// Details of this form
/// </summary>
public string description { get; set; }
/// <summary>
/// Minimum number of buyers
/// </summary>
public int lowBuNo { get; set; }
/// <summary>
/// Merchant address
/// </summary>
public string Address { get; set; }
/// <summary>
/// Merchant telephone number
/// </summary>
public string Telphone { get; set; }
/// <summary>
/// City area code
/// </summary>
public string cCode { get; set; }
/// <summary>
/// Folder name
/// </summary>
public string folderName { get; set; }
/// <summary>
/// Group purchase status
/// </summary>
public string StatusMessage { get; set; }
/// <summary>
/// Number of buyers now
/// </summary>
public int nownumber { get; set; }
/// <summary>
/// Commodity number
/// </summary>
public int productID { get; set; }
}
#endregion
Step 3: Get the database commodity information record and add it to the collection of objects (Arraylist):
#region Get xml Entity class information
/// <summary>
/// Get xml Entity class information
/// </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();
// City name
webModel.cityName = dr["cityName"].ToString();
// Commodity title
webModel.title = dr["title"].ToString();
// Commodity creation time
webModel.createtime = Convert.ToDateTime(dr["createtime"].ToString());
// Merchant name
webModel.merchants_id = dr["merchantsID"].ToString();
// Product picture
webModel.productimg = dr["productimg"].ToString();
// Market price
webModel.market_price = Convert.ToDecimal(dr["market_price"].ToString());
// Group purchase price
webModel.team_price = Convert.ToDecimal(dr["team_price"].ToString());
// Discounted price
webModel.zhekou_price = Convert.ToDecimal(dr["zhekou_price"].ToString());
// Start time
webModel.begin_time = Convert.ToDateTime(dr["begin_time"].ToString());
// End time
webModel.end_time = Convert.ToDateTime(dr["end_time"].ToString());
// Commodity description
webModel.description = dr["description"].ToString();
// Minimum purchase quantity
webModel.lowBuNo = Convert.ToInt32(dr["lowBuyNo"].ToString());
// Merchant telephone number
webModel.Telphone = dr["Tel"].ToString();
// Merchant address
webModel.Address = dr["Address"].ToString();
// City number
webModel.cCode = dr["cCode"].ToString();
// Picture folder name
webModel.folderName = dr["prodCode"].ToString();
// Number of buyers now
webModel.nownumber = Convert.ToInt32(dr["now_number"].ToString());
// Commodity number
webModel.productID = Convert.ToInt32(dr["id"].ToString());
int status = Convert.ToInt32(dr["statue"].ToString());
switch (status)
{
case 0:
webModel.StatusMessage = " End ";
break;
case 1:
webModel.StatusMessage = " Success ";
break;
}
list.Add(webModel);
}
}
return list;
}
#endregion
The last step is to assign the information read from the database to the XML data type and serialize it into an XML file, save it into a file in XML format, and display the read file to the interface:
#region Page loading Generated according to the number of commodity records in the database xml File information
/// <summary>
/// Page loading Generated according to the number of commodity records in the database xml File information
/// </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 = " Love to buy 114";
display.siteurl = "http://www.xxxxx.com/";
// City name
display.city = webInfo.cityName;
// Commodity title
display.webSitetitle = webInfo.title;
// Product picture
display.image = "http://211.155.235.30/tuangou/" + webInfo.folderName + "/" + webInfo.productimg;
// Commodity start time
display.startTime = webInfo.begin_time.ToShortDateString();
// Commodity end time
display.endTime = webInfo.end_time.ToShortDateString();
// Market price
display.value = Convert.ToDouble(webInfo.market_price);
// Group purchase price
display.price = Convert.ToDouble(webInfo.team_price);
// Discounted price
display.rebate = Convert.ToDouble(webInfo.zhekou_price);
// Number of people buying now
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);
// Construct string
StringBuilder sb = new StringBuilder();
// Writes a string to the stringWriter Object
StringWriter sw = new StringWriter(sb);
//xml Serialize object typeof( Class name )
XmlSerializer ser = new XmlSerializer(typeof(urlset));
// Put Stream Object and urlset1 Incoming from, serializing out 1 String sb
ser.Serialize(sw, urlsetList, xmlns);
sw.Close();
string FILE_NAME = HttpContext.Current.Server.MapPath("API/54tuan.xml");
FileInfo fi = new FileInfo(FILE_NAME);
// Delete the file if it already exists
if (fi.Exists)
{
if (fi.Attributes.ToString().IndexOf("ReadOnly") >= 0) {
fi.Attributes = FileAttributes.Normal;
}
File.Delete(fi.Name);
}
// Create a file And write the string
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();
}
// After the output is serialized, xml Documents
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
I hope this paper is helpful to everyone's asp. net programming.