Ads Top

XML Serialization and Deserialization in C#

Here we will learn how to implement XML serialization and deserialization in asp.net using c# with example:
First, we will do serialization of an object as below example.

1:  public static string SerializeObject(T Request)  
2:  {  
3:  string xmlString = string.Empty;  
4:  MemoryStream memoryStream = null;  
5:  XmlSerializer xs = null;  
6:  XmlTextWriter xmlTextWriter = null;  
7:  try  
8:  {  
9:  using (memoryStream = new MemoryStream())  
10:  {  
11:  xs = new XmlSerializer(Request.GetType());  
12:  xmlTextWriter = new XmlTextWriter(memoryStream, System.Text.Encoding.UTF8);  
13:  xs.Serialize(xmlTextWriter, Request);  
14:  memoryStream = (MemoryStream)xmlTextWriter.BaseStream;  
15:  System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();  
16:  xmlString = encoding.GetString(memoryStream.ToArray());  
17:  xmlString = xmlString.Substring(1, xmlString.Length - 1);  
18:  }  
19:  return xmlString;  
20:  }  
21:  catch  
22:  {  
23:  throw;  
24:  }  
25:  }  

Now, we will do deserialization of an object as below example:


1:  public static T DeserializeObject(string strXml)  
2:  {  
3:  XmlSerializer objSerializer = null;  
4:  StringReader objStringReader = null;  
5:  try  
6:  {  
7:  // Create an instance of the XmlSerializer specifying type and namespace.  
8:  objSerializer = new XmlSerializer(typeof(T));  
9:  using (objStringReader = new StringReader(strXml))  
10:  {  
11:  // Use the Deserialize method to restore the object's state.  
12:  return (T)objSerializer.Deserialize(objStringReader);  
13:  }  
14:  }  
15:  catch (Exception ex)  
16:  {  
17:  throw;  
18:  }  
19:  }  

Powered by Blogger.