Skip to content

Instantly share code, notes, and snippets.

@adhamankar
Created February 2, 2015 12:50
Show Gist options
  • Save adhamankar/a970bb9eca35bb82e3ae to your computer and use it in GitHub Desktop.
Save adhamankar/a970bb9eca35bb82e3ae to your computer and use it in GitHub Desktop.
XML Serialization helper code
public static class XmlSerializationUtil
{
public static string Serialize<T>(this T toSerialize)
{
XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
StringWriter textWriter = new StringWriter();
xmlSerializer.Serialize(textWriter, toSerialize);
return textWriter.ToString();
}
public static T Deserialize<T>(this string xml)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (TextReader reader = new StringReader(xml))
{
return (T)serializer.Deserialize(reader);
}
}
public static T DeserializeFile<T>(this string filename)
{
XmlSerializer _xmlSerializer = new XmlSerializer(typeof(T));
using (Stream stream = new FileStream(filename, FileMode.Open, FileAccess.Read))
{
var result = (T)_xmlSerializer.Deserialize(stream);
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment