2010-11-25 109 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%左右。

相關問題