traviblog

just some sort of lame blog

Embedding an XSLT as a string in a DLL binary

Project Properties - Resources

If you want to distribute a class library that relies on an XSL document and only want to worry about a single DLL then this is probably the easiest solution. In Visual Studio follow these commands (and save): Project Properties → Resources → Add Existing file

In this case, I am embedding a file named Core.xsl with a key named Core. That will generate a bit of code that looks like this:

~/Properties/Resources.resx:

<data name="Core" type="System.Resources.ResXFileRef, System.Windows.Forms">
	<value>..\Resources\Core.xsl;System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8</value>
</data>

~/Properties/Resources.Designer.cs:

public static string Core {
	get {
		return ResourceManager.GetString("Core", resourceCulture);
	}
}
XSL file properties

Be sure to set the properties of the file so that its Build Action is set as an Embedded Resource.

Now when you compile, the entire contents of the XSL file get embedded directly into the DLL as a string. You can now use the new property like this:

public static XslCompiledTransform GetXsl(XmlDocument xDoc)
{
	bool enableDocumentFunction = false;
	bool enableScript = true;
	XsltSettings xslSettings = new XsltSettings(enableDocumentFunction, enableScript);

	// only enable debugging in DEBUG mode
	bool isDebug = true;
#if (!DEBUG)
	isDebug = false;
#endif

	XslCompiledTransform xsl = new XslCompiledTransform(isDebug);
	xsl.Load(xDoc, xslSettings, new XmlUrlResolver());

	return xsl;
}

public static XslCompiledTransform GetXsl()
{
	XmlDocument xDoc = new XmlDocument();
	xDoc.LoadXml(Properties.Resources.Core);
	XslCompiledTransform xsl = GetXsl(null, xDoc);
	return xsl;
}

Previous XSLT stuff:

Compiling An XSLT Into A DLL Binary

Comments

comments powered by Disqus