2010-11-25 107 views
3

我有一个XElement对象,其中包含约120MB的数据。 XML由约6000个元素组成,每个元素大约20kb。XElement.ToString()导致System.OutOfMemoryException

我想拨打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(),这将是更少的内存密集?或者,我可以设置一些参数,以允许更大的内存空间?

+0

您需要在Web服务返回数据的120MB ... – Phill 2010-11-25 09:36:02

+0

这就是我在想... – 2010-11-25 09:39:12

回答

4

听起来好像你正在写的方式那里的数据太多; 一般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 - ,尤其是用于Web服务。你会开放的替代(更密集)序列化格式的建议?

0

我有同样的问题。

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

相关问题