XML 序列化 - 大数据 ( 20GB) , 内存不足异常.



我有一个问题:我想序列化一个xml(20GB(,但我得到一个out of memory异常。

你对此有什么建议吗?

我拥有的代码如下:

public static string Serialize(object obj)
{
    string retval = string.Empty;
    if (null!= obj)
    {
        StringBuilder sb = new StringBuilder();
        using (XmlWriter writer = XmlWriter.Create(sb, new XmlWriterSettings() { OmitXmlDeclaration = true }))
        {                    
            XmlSerializer serializer = new XmlSerializer(obj.GetType());
            // We are ommitting the namespace to simplifying passing as parameter
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("", "");
            serializer.Serialize(writer, obj);
        }
        retval = sb.ToString();
    }
    return retval;
}

> 20 GB 永远不会用作string(通过 StringBuilder(;即使启用了<gcAllowVeryLargeObjects>string的最大理论长度也只是其中的一小部分。

如果你想要大量的数据,你需要使用类似文件(或者基本上:一个不MemoryStream Stream(作为后端。

我还要说xml对于大数据来说是一个糟糕的选择。如果您没有严格绑定到 xml,我强烈建议您查看替代工具(如果可以选择,我很乐意提供建议(。

但就目前而言:

string path = "my.xml";
XmlWriterSettings settings = ...
using (XmlWriter writer = XmlWriter.Create(path, settings))
{
    // ...
}

或者,如果您实际上正在与插座等交谈:

Stream stream = ...
XmlWriterSettings settings = ...
using (XmlWriter writer = XmlWriter.Create(stream, settings))
{
    // ...
}

你可能有一个列表可以分块完成

        public static void Serialize(List<MyClass> myClasses)
        {
            string retval = string.Empty;
            if (myClasses != null)
            {
                using (StreamWriter sWriter = new StreamWriter("filename", false))
                {
                    foreach (MyClass myClass in myClasses)
                    {
                        StringBuilder sb = new StringBuilder();
                        using (XmlWriter writer1 = XmlWriter.Create(sb, new XmlWriterSettings() { OmitXmlDeclaration = true }))
                        {
                            XmlSerializer serializer = new XmlSerializer(myClass.GetType());
                            // We are ommitting the namespace to simplifying passing as parameter
                            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                            ns.Add("", "");
                            serializer.Serialize(writer1, myClass);
                        }
                        sWriter.Write(sb.ToString());
                    }
                }
            }
        }

最新更新