XElement.ToString()导致System.OutOfMemoryException

时间:2010-11-25 09:31:17

标签: c# asp.net xml memory

我有一个XElement对象,其中包含大约120MB的数据。 XML由大约6000个元素组成,每个元素大约20kb。

我正在尝试调用XElement.ToString(),因为我需要在Web服务中返回OuterXml。

我收到System.OutOfMemoryException

System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
   at System.String.GetStringForStringBuilder(String value, Int32 startIndex, Int32 length, Int32 capacity)
   at System.Text.StringBuilder.GetNewString(String currentString, Int32 requiredLength)
   at System.Text.StringBuilder.Append(Char[] value, Int32 startIndex, Int32 charCount)
   at System.IO.StringWriter.Write(Char[] buffer, Int32 index, Int32 count)
   at System.Xml.XmlEncodedRawTextWriter.FlushBuffer()
   at System.Xml.XmlEncodedRawTextWriter.WriteAttributeTextBlock(Char* pSrc, Char* pSrcEnd)
   at System.Xml.XmlEncodedRawTextWriter.WriteString(String text)
   at System.Xml.XmlEncodedRawTextWriterIndent.WriteString(String text)
   at System.Xml.XmlWellFormedWriter.WriteString(String text)
   at System.Xml.XmlWriter.WriteAttributeString(String prefix, String localName, String ns, String value)
   at System.Xml.Linq.ElementWriter.WriteStartElement(XElement e)
   at System.Xml.Linq.ElementWriter.WriteElement(XElement e)
   at System.Xml.Linq.XElement.WriteTo(XmlWriter writer)
   at System.Xml.Linq.XNode.GetXmlString(SaveOptions o)
   at System.Xml.Linq.XNode.ToString()

我在XmlDocument中拥有相同的数据,可以毫无问题地致电XmlDocument.OuterXml。我也可以调用XElement.Save()将XML保存到文件中而没有问题。

任何人都可以建议替代XElement.ToString(),这会减少内存密集吗?或者我可以设置一些允许更大内存空间的参数?

2 个答案:

答案 0 :(得分:4)

听起来你在那里写了 way 过多的数据; 通常原始XmlWriter可能是此卷的最佳选择。但是,如果你能Save()成功,你可以试试:

    string xml;
    using(var sw = new StringWriter()) {
        el.Save(sw);
        xml = sw.ToString();
    }

或者也许:

    string xml;
    using (var ms = new MemoryStream()) { 
        using(var tw = new StreamWriter(ms, Encoding.UTF8))
        {
            el.Save(tw);            
        }
        xml = Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Length);
    }

但是这些中的任何一个(或两者)可能仍会在火花中爆炸。您可能还想调查专为此类情景设计的XStreamingElement ...但是,对于网络服务而言,这仍然是很多xml - ,尤其是。您是否愿意接受替代(更密集)序列化格式的建议?

答案 1 :(得分:0)

我有同样的问题。

将WCF服务的transferMode设置为StreamedStreamedResponse。还可以在Web服务器上启用压缩,将下载大小降低到大小的10%左右。

相关问题