Convert C # XSLT from memory

All,

I have the code below for converting an XML document using XSLT. The problem is that in an XML document, about 12 MB in C # runs out of memory. Is there any other way to do the conversion without consuming so much memory?

public string Transform(XPathDocument myXPathDoc, XslCompiledTransform myXslTrans)
    {
        try
        {
            var stm = new MemoryStream();
            myXslTrans.Transform(myXPathDoc, null, stm);
            var sr = new StreamReader(stm);
            return sr.ReadToEnd();
        }
        catch (Exception e)
        {
          //Log the Exception
        }
    }

Here is the stack trace:

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.StreamReader.ReadToEnd()
at Transform(XPathDocument myXPathDoc, XslCompiledTransform myXslTrans)
+2
source share
6 answers

The first thing I would like to do is isolate the problem. Bring the entire MemoryStream business from the game and transfer the result to a file, for example:

using (XmlReader xr = XmlReader.Create(new StreamReader("input.xml")))
using (XmlWriter xw = XmlWriter.Create(new StreamWriter("output.xml")))
{
   xslt.Transform(xr, xw);
}

- ( ), , , - , , :

<xsl:template match="foo">
   <bar>
      <xsl:apply-templates select="."/>
   </bar>
</xsl:template>
+4

MemoryStream + ReadToEnd , 2 . 1 , StringWriter ( MemStream + Reader) writer.ToString(), .

24 , . - .
, , , XSLT .


var writer = new StringWriter();
//var stm = new MemoryStream();
myXslTrans.Transform(myXPathDoc, null, writer);
//var sr = new StreamReader(stm);
//return sr.ReadToEnd();
return writer.ToString();
+3

stm.Position = 0

reset StreamReader. .

+2

ReadToEnd() . XmlReader , xslt . XmlReader xslt, .

0

, , . = 0, .

public string Transform(XPathDocument myXPathDoc, XslCompiledTransform myXslTrans)
{
    try
    {
        using (var stm = new MemoryStream())
        {
             myXslTrans.Transform(myXPathDoc, null, stm);
             stm.Position = 0;
             using (var sr = new StreamReader(stm))
             {
                 return sr.ReadToEnd();
             }
        }
    }
    catch (Exception e)
    {
        //Log the Exception
    }
}
0

, JavaScript, .

. , , JavaScript XSLT .

, , . http://msdn.microsoft.com/en-us/magazine/cc302079.aspx

.Net-, -, XslTransform, JavaScript XSLT . JavaScript , , . , JavaScript. .

Another warning is to carefully use the new XslCompliedTransform class. With my large XSLT documents, I profiled the processor 4 times as compared to the XslTransform class and double its memory.

0
source

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


All Articles