Serialize and Deserialize (2)
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.Xml;
using System.IO;
public static class Utils
{
public static string Serialize(object o)
{
string xml;
XmlSerializer serializer = new XmlSerializer(o.GetType());
StringBuilder sb = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(sb))
{
serializer.Serialize(writer, o);
xml = sb.ToString();
}
return xml;
}
public static T Deserialize<T>(string xml)
{
if (xml == null)
return default(T);
T ret;
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (StringReader stream = new StringReader(xml))
{
ret = (T)serializer.Deserialize(stream);
}
return ret;
}
}
Related examples in the same category