Thursday, September 2, 2010

How to write XML File from the Object Collection

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;

public partial class WriteProductXMLFile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
WriteProducts("9955");
}
}

public System.Collections.IEnumerable CreateProducts()
{
List products = new List();


products.Add(Product.Create("1", "AAAA"));
products.Add(Product.Create("2", "BBBB"));
products.Add(Product.Create("3", "JJJJJ"));
products.Add(Product.Create("4", "AAAKKKA"));
products.Add(Product.Create("5", "YYYYY"));
products.Add(Product.Create("6", "PPPPP"));
products.Add(Product.Create("7", "MMMMM"));
products.Add(Product.Create("8", "TTTTT"));


return products;

}


protected void WriteProducts(string CustomerID)
{

System.Collections.IEnumerable products = CreateProducts();

string FileName = "Products_" + CustomerID+".xml";

string FilePath = Server.MapPath(FileName);

if (System.IO.File.Exists(FilePath))
{
System.IO.File.Delete(FilePath);
}

XmlTextWriter XmlWriter = new XmlTextWriter(FilePath, null);

XmlWriter.WriteStartDocument();
XmlWriter.WriteComment("Product XML.");
XmlWriter.WriteStartElement("Products of Customer: ID");

foreach (Product prod in products)
{

XmlWriter.WriteStartElement("Product");
XmlWriter.WriteElementString("ProductID", prod.ProductID);
XmlWriter.WriteElementString("ProductImage", prod.ProductImage);
XmlWriter.WriteEndElement();
}


XmlWriter.WriteEndDocument();
XmlWriter.Flush();
XmlWriter.Close();

}


# region Internal Class


public class Product
{
public static Product Create(string productID,
string productImage)
{
Product product = new Product();

product.ProductID = productID;
product.ProductImage = productImage;

return product;
}

private string _productID;

public string ProductID
{
get { return _productID; }
set { _productID = value; }
}

private string _Image;
public string ProductImage
{
get { return _Image; }
set { _Image = value; }
}

}

#endregion



}

No comments:

Post a Comment

 
Locations of visitors to this page