20 December 2013

Store the Object in XML File, and Get Back - C#

Hi Friends,

Let see how can we store the object in XML file and get back the object whenever needed.  Sometime we need to store the object or the collection of the objects of any class (Remember - Collection of the object is also a Object - list, array or whatever) anywhere and later point of time we required to get those object back.  You can do this by using serialization and deserialization.

You have to include the following class from in you project and call the Save and GetFromXML method to store and get the object back.

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

class SerializeDeserialize
{
  #region store the object in xml file at specify path
  public static void Save<T>(T obj, string path)
  {
    try
    {
      using (StreamWriter writer = new StreamWriter(path))
      {          
        XmlSerializer xs = new XmlSerializer(obj.GetType(),
          new XmlRootAttribute("RootNode"));
        XmlSerializerNamespaces xsn = new XmlSerializerNamespaces();
        xsn.Add("", "");          

        xs.Serialize(writer, obj, xsn);
      }
    }
    catch (Exception ex)
    {
      Console.WriteLine(ex.GetBaseException());
      return;
    }
  }
  #endregion



  #region get the object back from the xml file specified as path string
  public static T[] GetFromXML<T>(string Path)
  {
    T[] result = null;

    XmlRootAttribute xRoot = new XmlRootAttribute();
    xRoot.ElementName = "RootNode";
    xRoot.Namespace = "";
    xRoot.IsNullable = true;


    XmlSerializer ser = new XmlSerializer(typeof(T[]), xRoot);
      
    using (FileStream fs = new FileStream(Path, FileMode.Open))
    {
      XmlReader reader = XmlReader.Create(fs);
      try
      {
        result = (T[])ser.Deserialize(reader);
      }
      catch (Exception ex)
      {
        Console.WriteLine(ex.GetBaseException());
      }
    }

    return result;
  }
  #endregion
}
To store the object you just need to call the corresponding method, use the below syntax to call these method.
   ..
   ..
   ..
   List<MyClass> list = new List<MyClass>();
   list.Add(new MyClass("name1", "desc1", "path1"));  
   list.Add(new MyClass("name2", "desc2", "path2"));
   list.Add(new MyClass("name3", "desc3", "path3"));
   ..
   ..
   ..
   //Save the list created in xml file.
   SerializeDeserialize.Save<List<MyClass>>(list, @"C:\abc.xml");

   // get the array of the MyClass objects store in "abc.xml" file.
   MyClass[] ob = SerializeDeserialize.GetFromXML<MyClass>(@"C:\abc.xml");

   // Element count
   Console.WriteLine(ob.Length);

   // if element found in xml file print the properties of first object in ob
   if(ob.Length > 0 )
   {
     Console.WriteLine(ob[0].Name);
     Console.WriteLine(ob[0].Description);
     Console.WriteLine(ob[0].Path);
   }
When you call Save it will create the abc.xml file in C:\ driver.  The content in xml file will be-
<?xml version="1.0" encoding="utf-8"?>
<RootNode>
  <MyClass>
    <Name>name1</Name>
    <Description>desc1</Description>
    <Path>path1</Path>
  </MyClass>
  <MyClass>
    <Name>name2</Name>
    <Description>desc2</Description>
    <Path>path2</Path>
  </MyClass>
  <MyClass>
    <Name>name3</Name>
    <Description>desc3</Description>
    <Path>path3</Path>
  </MyClass>
</RootNode>


Thanks..!!
Happy Sharing.. !! :)

No comments:

Post a Comment