Memory leak with XML Transform method

Transform XML with XSLT, return XmlDocument

I used to use XSLT to transform XML that I get from a database and write the output to a file:

//Transforms Xml with Xslt and write to file
protected void TransformXmlToFile(XmlDocument xmlDoc, 
                                    string xsltPath, 
                                    string transformedXmlPath)
    XslTransform transform = new XslTransform();
    XmlTextWriter xmlWriter = new XmlTextWriter(transformedXmlPath);
    transform.Transform(xmlDoc, Nothing, xmlWriter, Nothing);

After some testing we started to experience problems with this approach as there is a a memory leak in MS XML 4.0 core services while using transform.Transform() function.


There are two options

  1. Install XML 6.0 which has more secured and more stable or
  2. Change the way the function is written.

I decided to rather transform the XML and return a XmlDocument as the output… the solution is to use a MemoryStream for the output and then load that into your XmlDocument. Or create a string or whatever you want to return:  


//Transforms Xml with Xslt and returns the transformed XmlDocument
protected XmlDocument TransformXml(XmlDocument xmlDoc, string xsltPath)
    MemoryStream memStream = new MemoryStream();
    XslTransform transform  = new XslTransform();

    transform.Transform(xmlDoc, Nothing, memStream, Nothing);

    memStream.Seek(0, SeekOrigin.Begin);

    XmlDocument transformedDoc = new XmlDocument();
    return transformedDoc.Load(memStream);



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s