As some of you know, there is an ongoing discussion whether Microsoft should/will support XSLT 2.0 in the next iteration of the .NET framework. Apparently, there are not enough resources (?) to implement both XQuery 1.0 and XSLT 2.0 so for now it looks like the latter will be implemented as it can be (and will be) also used in the database scenarios (looks more like SQL and is used in the similar way).
XSLT 1.0 compiled transform in the .NET 2.0 absolutely rocks, so not having a similar thing for the XSLT 2.0 is a bummer. Note that I am talking about invoking transformer right from your code, not from the command line. You could use free Altova’s AltovaXML tools but my experiments show the XSLT 2.0 engine is not nearly as conformant as it should be (chokes on simple demo files). Saxonica’s Saxon is great, but it’s written in Java and command line is the only option.
Or should I say was the only option. Since very recently (about a month ago) the effort to port Saxon to the .NET platform has been moved under the wings of Saxonica (it used to be a community project). The port is far from perfect as it uses IKVM and some of the APIs have slightly weird naming – methods that should be called CreateXXX are called NewXXX for example, but… it works and some parts of it are based on the .NET FCL.
The documentation is fairly complete but the latest download does not contain the C# samples mentioned on the Saxonica’s web site. So if you want to see some samples (and you will need to, as I will show just now) download both the latest version 8.7.1 and the previous version 8.7 of the resources.
To save you the trouble, or if you just want to see how a typical transform would look like, here it is:
using Saxon.Api;
internal class Program
{
[STAThread]
private static void Main(string[] args)
{
string source = @"c:\temp\input.xml";
string xslt = @"c:\temp\transform.xslt";
string dest = @"c:\temp\output.txt";
Processor p = new Processor();
XsltCompiler xc = p.NewXsltCompiler();
xc.BaseUri = new Uri(xslt);
using (FileStream tfs = new FileStream(xslt, FileMode.Open,
FileAccess.Read, FileShare.Read))
using (FileStream ifs = new FileStream(source, FileMode.Open,
FileAccess.Read, FileShare.Read))
using (FileStream ofs = new FileStream(dest, FileMode.Create,
FileAccess.Write, FileShare.None))
{
XsltExecutable xe = xc.Compile(tfs);
XsltTransformer xt = xe.Load();
DocumentBuilder db = p.NewDocumentBuilder();
db.BaseUri = new Uri(source);
xt.InitialContextNode = db.Build(ifs);
Serializer s = new Serializer();
s.SetOutputStream(ofs);
xt.Run(s);
}
}
}
This code can be simplified – to most of the constructs you can provide file names directly and not bother with the streams (but in real life usage you might already have streams that you got from somewhere).
This is great news for the .NET developers looking forward to using XSLT 2.0 in their projects straight from their code.
Be the first to rate this post
- Currently 0/5 Stars.
- 1
- 2
- 3
- 4
- 5