using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
public class Serialize
{
/// Used to serialize and then return xml string
///
/// T type
///
public static string SerializationObject(T obj)
{
try
{
string xmlstring = string.Empty;
MemoryStream memory = new MemoryStream();
XmlSerializer serialzer = new XmlSerializer(typeof(T));
XmlTextWriter writer = new XmlTextWriter(memory,Encoding.ASCII);
serialzer.Serialize(writer, obj);
memory = (MemoryStream)writer.BaseStream;
ASCIIEncoding encoding = new ASCIIEncoding();
xmlstring = encoding.GetString(memory.ToArray());
return xmlstring;
}
catch (Exception ex)
{
return string.Empty;
}
}
///
/// Used to Deserialize xml string and then return object
///
/// string xml serialized value
///
public static T DeserializationXMLString(string xmlString)
{
T obj = default(T);
try
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
StringReader stringReader = new StringReader(xmlString);
XmlTextReader xmlReader = new XmlTextReader(stringReader);
obj = (T)xmlSerializer.Deserialize(xmlReader);
xmlReader.Close();
stringReader.Close();
}
catch (Exception ex)
{ }
return obj;
}
/*Call the class*/
For serilization
Serialize
string xml=serialize.SerializationObject(class1 obj);
for deserialize
Serialize
class1 ca=new class1 ();
ca=serialize.DeserializationXMLString(xml);
Replies
Know the answer? Post it — somebody with the same question will find it here.