XElement.ToString () throws a System.OutOfMemoryException

I have an object XElementcontaining about 120 MB of data. XML consists of approximately 6,000 elements of 20 kB each.

I am trying to call XElement.ToString()as I need to return OuterXml to the webservice.

I get it 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()

I have the same data in XmlDocumentand can call XmlDocument.OuterXmlwithout problems. I can also call XElement.Save()to save the XML to a file without any problems.

Can anyone suggest an alternative to XElement.ToString () that will be less memory intensive? Or, alternatively, some parameters that I can set will increase the memory space?

+3
2

, ; raw 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 - -. ( ) ?

+4

.

WCF transferMode Streamed StreamedResponse. - 10% .

0

Source: https://habr.com/ru/post/1776853/


All Articles