Monday, 8 November 2010

Serialize and deserialize to XML string

private static string XmlSerialize(T obj)
    var stream = new MemoryStream();
    var writer = new XmlTextWriter(stream, Encoding.ASCII);

    XmlSerializer ser = new XmlSerializer(typeof(T));
    ser.Serialize(writer, obj);
    stream = (MemoryStream)writer.BaseStream;
    var bytes = stream.ToArray();
    var encoding = new UTF8Encoding();
    string result = encoding.GetString(bytes);

    return result;

private static T XmlDeserialize(string xml)
    XmlSerializer xs = new XmlSerializer(typeof(T));

    UTF8Encoding encoding = new UTF8Encoding();
    Byte[] byteArray = encoding.GetBytes(xml);

    MemoryStream memoryStream = new MemoryStream(byteArray);
    XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
    object obj = xs.Deserialize(memoryStream);
    return (T)obj;

No comments:

Post a Comment