Tuesday, May 01, 2007

Convert XML data to object and back using serialization

Introduction -
This article shows you how to convert an XML to a class object and retriving back.

Saving XML to a class object is called serialization and reading back using the reverse process is called as deserialization.
1> Assuming you have a sample xsd, to convert a class from XSD, we would run the following command:

xsd C:\Contact.xsd /t:lib /l:cs /c from VS.net command prompt.
2> /// auto generated code from xsd command ran above...
using System.Xml.Serialization;
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public class Contact
{        
public ContactInfo;
}
public class ContactInfo
{        
public string Code;        
public string FirstName;        
public string LastName;        
public string Email;
}
 
3> Now, we could save an contact XML data to this class using this simple function:
public Contact ContactObject(string xml)  
{   
StringReader stream = null;   
XmlTextReader reader = null;   
try   
{    
// serialise to object    
XmlSerializer serializer = new XmlSerializer(typeof(Contact));
stream = new StringReader(xml); // read xml data    
reader = new XmlTextReader(stream);  // create reader    
// covert reader to object    
return (Contact)serializer.Deserialize(reader);   
}   
}
 
And to get the XML based on the Contact class object, use the following function:
public string ContactXML(Contact cont)  
{   
MemoryStream stream = null;   
TextWriter writer = null;   
try   
{    
stream = new MemoryStream(); 
// read xml in memory    
writer = new StreamWriter(stream, Encoding.Unicode) ;    
// get serialise object    
XmlSerializer serializer = new XmlSerializer(typeof(Contact));    
serializer.Serialize(writer, cont); 
// read object    
int count = (int) stream.Length; 
// saves object in memory stream    
byte[] arr = new byte[count];    
stream.Seek(0, SeekOrigin.Begin);    
// copy stream contents in byte array    
stream.Read(arr, 0, count);    
UnicodeEncoding utf = new UnicodeEncoding(); 
// convert byte array to string    
return utf.GetString(arr).Trim();   
}   
}
 
Hope this helps for all working on XML!
Thanks - DJ

No comments: