C# Xml Serialization & Deserialization

In your deserialization code you’re creating a MemoryStream and XmlTextWriter but you’re not giving it the string to deserialize.

using (MemoryStream memStream = new MemoryStream())
{
    using (XmlTextWriter textWriter = new XmlTextWriter(memStream, Encoding.Unicode))
    {
        // Omitted
    }
}

You can pass the bytes to the memory stream and do away with the XmlTextWriter altogether.

using (MemoryStream memStream = new MemoryStream(Encoding.Unicode.GetBytes(xmlString)))
{
    System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
    return (T)serializer.Deserialize(memStream);
}

Leave a Comment