Friday, May 20, 2016

Read xml file into list with C#


      1.Create an xml file in below format

  xml version="1.0" encoding="utf-8" ?>
   <ArrayOfProduct>
     <Product>
       <Id>1</Id>
       <Name>product 1</Name>
       <Price>20000</Price>
     </Product>
     <Product>
       <Id>2</Id>
       <Name>product 2</Name>
       <Price>15000</Price>
     </Product>
   </ArrayOfProduct>

      2.Create a property class for the xml file

public class Product
       {
              public int Id { getset; }
              public string Name { getset; }
              public float Price { getset; }
}



3. Include these namespaces

using System.Xml.Serialization;
using System.IO;     

4.       Read xml to list

List<Product> lstProduct;
//Datas/Product.xml is the relative path of xml file.
string folderPath = System.Web.HttpContext.Current.Server.MapPath("~/Datas/Product.xml"); 
       XmlSerializer serializer = new XmlSerializer(typeof(List<Product>));
       using (FileStream fs = new FileStream(folderPath, FileMode.Open,FileAccess.Read))
       {
     //Deserialize to Product list.
            lstProduct = (List<Product>)serializer.Deserialize(fs);
       }
//lstProduct contains the result.

5.   Read Xml as a generic method
 /// 
        /// Read the xml to list.
        /// 

        /// Class Name.

        /// Relative path of xml file."
        /// List of objects of specific type.

        public List ReadXml(string relativePath)
        {
            List lstResult = null;
            try
            {
                string folderPath = System.Web.HttpContext.Current.Server.MapPath(relativePath);
                XmlSerializer serializer = new XmlSerializer(typeof(List));
                using (FileStream fs = new FileStream(folderPath,FileMode.Open, FileAccess.Read))
                {
                    lstResult = (List)serializer.Deserialize(fs);
                }
            }
            catch (Exception ex)
            {

            }
            return lstResult;
}


           6.     Call the generic method

       //Read Product.xml to list of products.
List<Product> lstProduct = ReadXml<Product>("~/Datas/Product.xml");

No comments:

Post a Comment