How to embed an Xslt-file in an assembly

Problem
How do I embed an Xslt file into an assembly so that I won’t have to deploy the file together with the assembly, set configuration options to refer to the file, etc?

Solution

  1. Create a resource (.resx) file in the project
  2. In the resource designer, click “Add Resource” and choose “Add Existing File…”. Select the Xslt file.
  3. Give the new resource a describing name, such as “FilterContentXslt”. The contents of the Xslt file will be available in a string property with this name in the Resource manager.
  4. Code that performs the transformation:
    // Parse the content into an XmlDocument
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(xmlValue);
    
    // Retrieve the embedded resource containing the XSLT transform
    XmlDocument xsltDoc = new XmlDocument();
    xsltDoc.LoadXml(Resources.FilterContentXslt);
    
    XslCompiledTransform trans = new XslCompiledTransform();
    trans.Load(xsltDoc);
    
    // Perform the transformation
    StringWriter writer = new StringWriter();
    trans.Transform(doc, writer);
    string newXmlValue = writer.ToString();
    

Simple, and it works.

/Emil

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.