Convert the User Defined Class to XML and Vice Versa

In our application we have faced situations such as storing data in XML and retrieving back the value from XML. For this we will write the code to store and retrieve the data, but we can achieve this easily using XmlSerializer, StringWriter, XmlTextWriter. These three classes performs this operation in an easy manner.

For Converting the object to XML,

  1. public string GetXMLFromObject(object obj)  
  2. {  
  3.    XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType());  
  4.    StringWriter stringWriter = new StringWriter();  
  5.    XmlWriter xmlWriter = new XmlTextWriter(stringWriter);  
  6.    xmlSerializer.Serialize(xmlWriter, obj);  
  7.    return stringWriter.ToString();  
  8.   
  9. }  
For Converting the XML to Object
  1. public static object GetObjectFromXML(string xml,Type objType)  
  2. {  
  3.    StringReader stringReader = new StringReader(xml);  
  4.    XmlReader xmlReader = new XmlTextReader(stringReader);  
  5.    XmlSerializer xmlSerializer = new XmlSerializer(objType);  
  6.    return xmlSerializer.Deserialize(xmlReader);  
  7. }