Monday, October 8, 2012

.NET equivalent of xslproc

Recently I had to install xslproc tool on windows  for an open source project i'm contributing to.  All I can say is - annoying.  I decided to use the power of .Net to write a drop-in replacement. The main goal was not to change any of the scripts that call this tool and not to have any dependencies besides .NET Framework. My code is below. Not counting the error handling code, core logic is only 4 lines long. The miracle worker here is the XslCompiledTransform class.

 Please note that it only supports limited subset of parameters of the original tool. Use at your own risk.

static int Main(string[] args)
        {
            if (args == null || args.Length != 4)
            {
                Console.Error.WriteLine("Invalid arguments provided!" + args.Length);
 
                return -1;
 
            }
 
            string outFile = args[1];
            string styleSheet = args[2];
            string inputFile = args[3];
 
            try
            {
                XslCompiledTransform myXslTransform = new XslCompiledTransform();
 
                myXslTransform.Load(Path.Combine(Environment.CurrentDirectory, styleSheet));
 
                myXslTransform.Transform(Path.Combine(Environment.CurrentDirectory, inputFile), Path.Combine(Environment.CurrentDirectory, outFile));
               
                return 0;
            }
            catch (Exception ex)
            {
 
                Console.Error.WriteLine("Error during transform: " + ex.ToString());
 
                return -1;
 
 
            }
        }