Programming: Serialize/Deserialize to/from XML

Tags: xml, serialize

Sometimes you need to store data. We use this snippet to serialize and deserialize objects and store settings in a Database.
So we can use a simple Name/Value combination for our settings.

public static string SerializeObject<T>(T value) {
    MemoryStream memoryStream = new MemoryStream();
    XmlSerializer serializer = new XmlSerializer(typeof(T));
    XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
    serializer.Serialize(xmlTextWriter, value);
    UTF8Encoding encoding = new UTF8Encoding();
    return encoding.GetString(memoryStream.ToArray());
}

public static T DeSerializeObject<T>(string value) {
    UTF8Encoding encoding = new UTF8Encoding();
    MemoryStream memoryStream = new MemoryStream(encoding.GetBytes(value));
    XmlSerializer serializer = new XmlSerializer(typeof(T));
    return (T)serializer.Deserialize(memoryStream);
}

Greets – Helmut

Add a Comment