Skip to content

Instantly share code, notes, and snippets.

@miklund
Last active January 15, 2016 19:33
Show Gist options
  • Save miklund/badcac4e2b12d160843e to your computer and use it in GitHub Desktop.
Save miklund/badcac4e2b12d160843e to your computer and use it in GitHub Desktop.
2009-03-04 Extending XSLT
# Title: Extending XSLT
# Author: Mikael Lundin
# Link: http://blog.mikaellundin.name/2009/03/04/extending-xslt.html
XslCompiledTransform transformer = new XslCompiledTransform(debug);
XsltSettings settings = new XsltSettings(false, false); // document() and script disabled
XsltArgumentList arguments = new XsltArgumentList();
arguments.AddExtensionObject("urn:mint", new XsltExtensions());
transformer.Load(XmlReader.Create(stylesheetStream), settings, null);
transformer.Transform(XmlReader.Create(documentStream), arguments, output);
/// <summary>
/// An extension class for an XSL transformation
/// </summary>
public interface IXsltExtensions
{
/// <summary>
/// Gets the namespace URI that associates this class with a namespace in the xslt.
/// </summary>
/// <value>The namespace URI.</value>
string NamespaceUri { get; }
}
/// <summary>
/// Loads the XSLT extensions into the argument list
/// </summary>
/// <param name="arguments">The argumentlist that will be used in transfomation</param>
private void LoadExtensions(XsltArgumentList arguments)
{
// Retrieve all implementations of IXsltExtensions
IEnumerable<IXsltExtensions> extensions = ContainerFactory.Instance.ResolveAll<IXsltExtensions>();
// Add all implementations as extensions to the transformation
foreach (IXsltExtensions extensionObject in extensions)
arguments.AddExtensionObject(extensionObject.NamespaceUri, extensionObject);
}
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:mint="urn:mint">
<xsl:output method="xhtml" encoding="utf-8" indent="yes" media-type="application/xhtml+xml" />
<xsl:template match="/">
<html>
<head>
<title>
<xsl:value-of select="//title" />
</title>
</head>
<body>
<h1>Value of parameter test is: <xsl:value-of select="mint:parameter('test')" /></h1>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
/// <summary>
/// Default extensions for Mint transformations
/// </summary>
public class XsltExtensions
{
/// <summary>
/// Returns parameter of the current HttpContext.Request
/// </summary>
/// <param name="parameterName">Name of the parameter to retrieve</param>
/// <returns>String.Empty if parameter is not found</returns>
public string parameter(string parameterName)
{
return HttpContext.Current.Request.Params[parameterName] ?? string.Empty;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment