Tuesday, May 5, 2009

C# - Sample code - System.Xml.Serialization and XML serialization attributes



[XmlRoot ("Produts")]
public class product2Sell
{
[XmlAttribute] public int prdId;
public string prdName;
public decimal prdPrice;
public int prdQty;
public DateTime prdLastOrderDate;
[XmlIgnore] public DateTime prdLastShipDate;

public product2Sell()
{
}
}



private void btnXmlSerialize_Click(object sender, EventArgs e)
{
List lstProduct = new List();
for (int i = 0; i < 3; i++)
{
product2Sell prdItem = new product2Sell();
prdItem.prdId = i;
prdItem.prdName = "Product" + i.ToString();
prdItem.prdPrice = i * 10.75m;
prdItem.prdQty = i * 3 + 5;
prdItem.prdLastOrderDate = DateTime.Now.AddDays(-i * 3);
prdItem.prdLastShipDate = DateTime.Now.AddDays(i * 2);

lstProduct.Add(prdItem);
}

string fName = @"C:\FB\Tst.data";
using (FileStream fs = new FileStream(fName, FileMode.Create))
{
XmlSerializer xs = new XmlSerializer( typeof(List) );
xs.Serialize(fs, lstProduct);
}
}

private void btnXmlDeserialize_Click(object sender, EventArgs e)
{
string fName = @"C:\FB\Tst.data";
using (FileStream fs = new FileStream(fName, FileMode.Open))
{
XmlSerializer xs =
new XmlSerializer(typeof(List) );
List lstPrdItem =
(List) xs.Deserialize(fs);

MessageBox.Show("# of products: " + lstPrdItem.Count.ToString());
}
}

Share/Bookmark

No comments: