如何将对象序列化为xml并在内存中进行压缩

时间:2014-04-22 07:32:32

标签: c# xml serialization xml-serialization gzipstream

在我的应用程序中,我需要将大对象序列化为xml字符串。但随后序列化抛出System.OutOfMemory异常。如何在没有异常和压缩的情况下序列化对象?

public static string GenerateXMLData<T>(T data)
    {
        byte[] bytes;
        using (var memoryStream = new MemoryStream())
        {
            using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Compress))
            {
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                binaryFormatter.Serialize(gZipStream, data);
            }
            bytes = memoryStream.ToArray();
        }

        return Encoding.UTF8.GetString(bytes);
    }

1 个答案:

答案 0 :(得分:0)

这里有很多关于stackoverflow的好回复,可以通过快速Google搜索来加入这里是我找到的

Serialize an object to XML

另一个我不得不用一段时间回来

How to make a serializable class that contains an instance of one class from a set of classes

希望它有助于交配:)

相关问题