/// <summary> /// Load the XSLT file /// </summary> public void Load(string filename, bool profilingEnabled = false) { //register our eval() function processor = new Processor(); processor.RegisterExtensionFunction(new SaxonEvaluate(processor.NewXPathCompiler())); //tracing if (profilingEnabled) { var profile = new TimingTraceListener(); processor.Implementation.setTraceListener(profile); processor.Implementation.setLineNumbering(true); processor.Implementation.setCompileWithTracing(true); processor.Implementation.getDefaultXsltCompilerInfo().setCodeInjector(new TimingCodeInjector()); profile.setOutputDestination(new java.io.PrintStream("profile.html")); } //capture the error information var compiler = processor.NewXsltCompiler(); compiler.ErrorList = errorList; //compile the stylesheet var relativeFilename = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filename); try { var exec = compiler.Compile(XmlTextReader.Create(relativeFilename)); //capture xsl:message output transform = exec.Load(); transform.MessageListener = new SaxonMessageListener(); } catch (Exception) { foreach (StaticError err in compiler.ErrorList) { log.ErrorFormat("{0} ({1}, line {2})", err, err.ModuleUri, err.LineNumber); } throw; } }
void RegisterExtensionFunctions(Processor processor, SaxonItemFactory itemFactory) { IEnumerable<IEnumerable<Type>> builtInFunctions = new IEnumerable<Type>[] { new modules.exslt.common.Index(), new modules.request.Index(), new modules.response.Index(), new modules.session.Index(), new modules.util.Index(), new modules.validation.Index(), new modules.smtpclient.Index(), new modules.expath.httpclient.Index(), }; IEnumerable<IEnumerable<Type>> importedFunctions = (from m in XPathModules.GetModuleAdaptersForProcessor(this.GetType()) let t = m.AdapterType let isCollection = typeof(IEnumerable<Type>).IsAssignableFrom(t) select (isCollection) ? (IEnumerable<Type>)Activator.CreateInstance(t) : new Type[] { t }); Type itemFactoryType = itemFactory.GetType(); foreach (var types in Enumerable.Concat(builtInFunctions, importedFunctions)) { var functions = from t in types let ctor = t.GetConstructors().First() let param = ctor.GetParameters() let args = param.Select(p => p.ParameterType.IsAssignableFrom(itemFactoryType) ? (object)itemFactory : null).ToArray() select (ExtensionFunctionDefinition)ctor.Invoke(args); if (functions.Select(f => f.FunctionName.Uri).Distinct().Count() > 1) throw new InvalidOperationException("Functions in module must belog to the same namespace."); foreach (var fn in functions) processor.RegisterExtensionFunction(fn); } }
/// <summary> /// Show a transformation using calls to extension functions /// </summary> public override void run(Uri samplesDir) { // Create a Processor instance. Processor processor = new Processor(); // Identify the Processor version Console.WriteLine(processor.ProductVersion); // Set diagnostics //processor.SetProperty("http://saxon.sf.net/feature/trace-external-functions", "true"); // Create the stylesheet String s = @"<xsl:transform version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'" + @" xmlns:math='http://example.math.co.uk/demo'> " + @" <xsl:template name='go'> " + @" <out sqrt2='{math:sqrt(2.0e0)}' " + @" sqrtEmpty='{math:sqrt(())}'/> " + @" </xsl:template></xsl:transform>"; // Register the integrated extension function math:sqrt processor.RegisterExtensionFunction(new Sqrt()); // Create a transformer for the stylesheet. XsltTransformer transformer = processor.NewXsltCompiler().Compile(new StringReader(s)).Load(); // Set the root node of the source document to be the initial context node transformer.InitialTemplate = new QName("go"); // Create a serializer Serializer serializer = new Serializer(); serializer.SetOutputWriter(Console.Out); serializer.SetOutputProperty(Serializer.INDENT, "yes"); // Transform the source XML to System.out. transformer.Run(serializer); }
/// <summary> /// Demonstrate XSLT extensibility using user-written extension functions /// </summary> /// <remarks>Note: If SamplesExtensions is compiled to a different assembly than ExamplesPE, use /// the namespace URI clitype:SampleExtensions.SampleExtensions?asm=ASSEMBLY_NAME_HERE /// </remarks> public override void run(Uri samplesDir) { // Create a Processor instance. Processor processor = new Processor(); // Identify the Processor version Console.WriteLine(processor.ProductVersion); // Set diagnostics //processor.SetProperty("http://saxon.sf.net/feature/trace-external-functions", "true"); // Create the stylesheet String s = @"<xsl:transform version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'" + @" xmlns:ext='clitype:SampleExtensions.SampleExtensions?asm=ExamplesPE' " + @" xmlns:tz='clitype:System.TimeZone' " + @" xmlns:math='http://example.math.co.uk/demo' " + @" xmlns:env='http://example.env.co.uk/demo' " + @" exclude-result-prefixes='ext math env tz'> " + @" <xsl:param name='timezone' required='yes'/> " + @" <xsl:template match='/'> " + @" <out addition='{ext:add(2,2)}' " + @" average='{ext:average((1,2,3,4,5,6))}' " + @" firstchild='{ext:nameOfFirstChild(.)}' " + @" timezone='{tz:StandardName($timezone)}' " + @" sqrt2='{math:sqrt(2.0e0)}' " + @" defaultNamespace='{env:defaultNamespace()}' " + @" sqrtEmpty='{math:sqrt(())}'> " + @" <xsl:copy-of select='ext:FirstChild((//ITEM)[1])'/> " + @" <defaultNS value='{env:defaultNamespace()}' xsl:xpath-default-namespace='http://default.namespace.com/' /> " + @" <combine1><xsl:sequence select='ext:combine(ext:FirstChild((//ITEM)[1]), count(*))'/></combine1> " + @" <combine2><xsl:sequence select='ext:combine((//TITLE)[1], (//AUTHOR)[1])'/></combine2> " + @" </out> " + @" </xsl:template></xsl:transform>"; // Register the integrated extension functions math:sqrt and env:defaultNamespace processor.RegisterExtensionFunction(new Sqrt()); processor.RegisterExtensionFunction(new DefaultNamespace()); // Create a transformer for the stylesheet. XsltTransformer transformer = processor.NewXsltCompiler().Compile(new StringReader(s)).Load(); // Load the source document (must be a wrapper around an XmlDocument for this test) XmlDocument doc = new XmlDocument(); doc.Load(new XmlTextReader(samplesDir.AbsolutePath + "data/books.xml")); XdmNode input = processor.NewDocumentBuilder().Wrap(doc); // Set the root node of the source document to be the initial context node transformer.InitialContextNode = input; // Supply a parameter transformer.SetParameter(new QName("", "timezone"), XdmAtomicValue.WrapExternalObject(TimeZone.CurrentTimeZone)); // Create a serializer Serializer serializer = new Serializer(); serializer.SetOutputWriter(Console.Out); serializer.SetOutputProperty(Serializer.INDENT, "yes"); // Transform the source XML to System.out. transformer.Run(serializer); }
static void Main(string[] args) { var proc = new Processor(); proc.RegisterExtensionFunction(new MakeRelativeUriExtensionFunction()); var compiler = proc.NewXsltCompiler(); string currentDir = Environment.CurrentDirectory; string inputDir = args[0]; string outputDir = args[1]; if (currentDir.Last() != Path.DirectorySeparatorChar) { currentDir += Path.DirectorySeparatorChar; } if (inputDir.Last() != Path.DirectorySeparatorChar) { inputDir += Path.DirectorySeparatorChar; } if (outputDir.Last() != Path.DirectorySeparatorChar) { outputDir += Path.DirectorySeparatorChar; } var baseUri = new Uri(AppDomain.CurrentDomain.BaseDirectory, UriKind.Absolute); var callerBaseUri = new Uri(currentDir, UriKind.Absolute); var sourceUri = new Uri(callerBaseUri, inputDir); var outputUri = new Uri(callerBaseUri, outputDir); var exec = compiler.Compile(new Uri(baseUri, "sandcastle-md-all.xsl")); var transformer = exec.Load(); transformer.InitialTemplate = new QName("main"); transformer.SetParameter(new QName("source-dir"), new XdmAtomicValue(sourceUri)); if (args.Length > 1) { transformer.SetParameter(new QName("output-dir"), new XdmAtomicValue(outputUri)); } var serializer = new Serializer(); serializer.SetOutputWriter(Console.Out); transformer.Run(serializer); var iconsSourceUri = new Uri(sourceUri, "icons"); var iconsDestUri = new Uri(outputUri, "_icons"); DirectoryInfo iconsSourceDir = new DirectoryInfo(iconsSourceUri.LocalPath); DirectoryInfo iconsDestDir; if (!Directory.Exists(iconsDestUri.LocalPath)) { iconsDestDir = Directory.CreateDirectory(iconsDestUri.LocalPath); } else{ iconsDestDir = new DirectoryInfo(iconsDestUri.LocalPath); } var icons = new HashSet<string>(File.ReadAllLines(new Uri(baseUri, "icons.txt").LocalPath), StringComparer.OrdinalIgnoreCase); foreach (FileInfo iconFile in iconsSourceDir.GetFiles()) { if (icons.Contains(iconFile.Name)) { iconFile.CopyTo(Path.Combine(iconsDestDir.FullName, iconFile.Name), overwrite: true); } } }
void RegisterExtensionFunctions(Processor processor, SaxonItemFactory itemFactory) { ExtensionFunctionDefinition[] precompiledFunctions = extensions.exslt.common.Index.GetFunctions() .Concat(extensions.w3c.xpath.math.Index.GetFunctions()) .Concat(extensions.saxon.Index.GetFunctions(itemFactory)) .ToArray(); bool[] funcAvailable = FunctionsAvailable(precompiledFunctions.Select(d => d.FunctionName).ToArray(), processor, itemFactory); for (int i = 0; i < precompiledFunctions.Length; i++) { if (!funcAvailable[i]) { processor.RegisterExtensionFunction(precompiledFunctions[i]); } } Type itemFactoryType = itemFactory.GetType(); var fnGen = new IntegratedExtensionFunctionGenerator(); foreach (Type t in fnGen.Generate(XPathModules.Modules)) { ConstructorInfo ctor = t.GetConstructors().First(); object[] args = ctor.GetParameters().Select(p => p.ParameterType.IsAssignableFrom(typeof(SaxonProcessor)) ? (object)this : p.ParameterType.IsAssignableFrom(itemFactoryType) ? (object)itemFactory : null ).ToArray(); var def = (ExtensionFunctionDefinition)ctor.Invoke(args); processor.RegisterExtensionFunction(def); } }