Serialize to and from XML
Category: DotNet
Do you ever have an object lying around that you would like to save off to the database and then be able to retrieve it later as that same object type? Then this might help you. Note that it only works with class objects that are serializable, and these must have a parameterless constructor.
They come in handy to serialize Generic List objects too.
public static string SerializeToString(object obj)
{
string output = null;
if (obj != null)
{
XmlSerializer serializer = new XmlSerializer(obj.GetType());
using (StringWriter writer = new StringWriter())
{
serializer.Serialize(writer, obj);
output = writer.ToString();
}
}
return output;
}
And then to serialize back into the object:
public static T SerializeFromString(string xml) { XmlSerializer serializer = new XmlSerializer(typeof(T)); using (StringReader reader = new StringReader(xml)) { return (T)serializer.Deserialize(reader); } }