Wednesday, November 7, 2012

Load XslCompiledTransform different ways

static XslCompiledTransform LoadXslt(string source)
{
    XslCompiledTransform XmlOutputTransform = null;
    if (source.StartsWith("@"))
    {
        // @ indicates file input
        if (source.Substring(1).EndsWith(".dll"))
        {
            // precompiled transform, first type
            Assembly a = Assembly.LoadFile(
                source.Substring(1)
            );
            XmlOutputTransform = new XslCompiledTransform();
            XmlOutputTransform.Load(a.GetTypes()[0]);
        }
        else if (source.Contains(".dll@"))
        {
            // precompiled transform, specified type
            string[] split = source.Substring(1).Split(
                "@".ToCharArray()
            );
            Assembly a = Assembly.LoadFile(split[0]);
            XmlOutputTransform = new XslCompiledTransform();
            XmlOutputTransform.Load(a.GetType(split[1]));
        }
        else
        {
            XmlOutputTransform = new XslCompiledTransform();
            XmlOutputTransform.Load(source.Substring(1));
        }
    }
    else
    {
        // presume source contains raw Xml;
        XmlOutputTransform = new XslCompiledTransform();
        XmlOutputTransform.Load(XmlReader.Create(
            new MemoryStream(
                ASCIIEncoding.Default.GetBytes(source)
            )
        );
    }
    return XmlOutputTransform;
}