Simple C# XSL Transformation

Published Tue, Apr 13 2004 23:06 | coad

“XSLTransform.cs”

                                    

And here is a simple C# translator that takes an XML file sends it through an XSL file transform and saves the output.  It is intended to be used as a console application.  This can be easily used to apply the CSV transform XSL to Vocabulary.xml.

 

 

// Created by Noah Coad, coad.net/noah, noah@coad.net, 4/10/04

 

using System;

using System.IO;

using System.Xml;

using System.Xml.Xsl;

using System.Diagnostics;

 

namespace XSLTransform

{

   class Transform

   {

      private Transform(string[] args)

      {

         // Make sure at least three command

         // line arguments are specified

         if (args.Length < 3) {ShowSyntax(); return;}

 

         XslTransform xsl = new XslTransform();

 

         // Attempt to load the XSL

         try {xsl.Load(args[1]);}

         catch (XmlException e) {Console.WriteLine("Could not load XSL transform: " + args[1] + "\n\n" + e.Message); return;}

         catch (XsltException e) {Console.WriteLine("Could not process the XSL: " + args[1] + "\n\n" + e.Message + "\nOn line " + e.LineNumber + " @ " + e.LinePosition); return;}

 

         // Attempt to transform the XML

         try {xsl.Transform(args[0], args[2]);}

         catch (XmlException e) {Console.WriteLine("Could not perform transform on: " + "\n\n" + e.Message); return;}

      }

 

      [STAThread]

      static void Main(string[] args)

      { new Transform(args); }

 

      private void ShowSyntax()

      { Console.Write("XSLTransform Xml-URL Xsl-URL Output.txt"); }

   }

}

 

 

 

Filed under: ,

Comments

# coad said on May 29, 2005 5:40 PM:

Cool, I appreciate the simplicity of this very much : )

My Visual Studio 2003 claims that this method is obsolete:

xsl.Transform(xmlFileName, outputFileName);

...Any ideas how to comply with the suggested change?

# James Vaughan said on August 14, 2006 11:21 AM:

XslCompiledTransform is the new class to do this with.  It should be really easy to convert between the two.