c# .net code snippet to cache xslt objects

XslCompiledTransform class is used to perform xslt transformation. Construction of the instance of the object of this type takes some time as it has to load, parse and compile xslt file and all the includes. You have to think about caching of the XslCompiledTransform object instance if your application uses xslt transformation based on the same xslt file more than once.

var xslFilePath = "path\\to\\your\\xsl\\file";
ObjectCache cache = MemoryCache.Default; // I used MemoryCache - there are more possibilities
//Check if there is something in the cache. Cache key is xslt file path
var xsl = cache[xslFilePath] as XslCompiledTransform;
if (xsl == null)
// If nothing construct the XslCompiledTransform objects instance and cache it
xsl = new XslCompiledTransform();
var xsltSettings = new XsltSettings(false, true);
xsl.Load(xslFilePath, xsltSettings, new XmlUrlResolver());
var policy = new CacheItemPolicy();
List paths = null;
// retrieve all the dependent file paths
ConstructCacheItemPolicy(xslFilePath,ref paths);
policy.ChangeMonitors.Add(new HostFileChangeMonitor(paths));
var ms = new MemoryStream();
xsl.Transform(xInput, null, ms);
ms.Position = 0;
var result = ms;

A function to collect all the dependent xslt includes for the cache dependency

private static void ConstructCacheItemPolicy(string xslFilePath, ref List paths )
// Add current xslt file path into our result set
if (paths == null) paths = new List();
if (!paths.Contains(xslFilePath)) paths.Add(xslFilePath);
var xmlDocument=new XmlDocument();
// load xslt file into XmlDocument
// Take care of xml namespaces
var xmlNamespaceManager = new XmlNamespaceManager(xmlDocument.NameTable);
// Select includes
var xNL = xmlDocument.SelectNodes("//xsl:include",xmlNamespaceManager);
if (xNL != null)
// iterated through the includes and perform recursive iterations to collect everything what is in scope
foreach (XmlElement xE in xNL)
var pathRoot = Path.GetDirectoryName(xslFilePath);
if (pathRoot != null)
var xslIncludeFilePath = Path.Combine(pathRoot, xE.GetAttribute("href"));
ConstructCacheItemPolicy(xslIncludeFilePath, ref paths);

Leave a Reply