Project

Profile

Help

How to connect?
Download (92.3 KB) Statistics
| Branch: | Tag: | Revision:

he / tags / 9.9.0.2 / samples / cs / ExamplesEE.cs @ c74fd4aa

1
using System;
2
using System.IO;
3
using System.Collections;
4
using System.Xml;
5
using System.Net;
6
using Saxon.Api;
7

    
8

    
9
namespace SaxonEE
10
{
11
    class ExamplesEE
12
    {
13
        /// <summary>
14
        /// Run Saxon XSLT and XQuery sample applications for Saxon Enterprise Edition on .NET
15
        /// </summary>
16
        /// <param name="argv">
17
        /// <para>Options:</para>
18
        /// <list>
19
        /// <item>-test:testname  run a specific test</item>
20
        /// <item>-dir:samplesdir directory containing the sample data files (default %SAXON_HOME%/samples)</item>
21
        /// <item>-ask:yes|no     indicates whether to prompt for confirmation after each test (default yes)</item>
22
        /// </list>
23
        /// </param>
24

    
25

    
26
        public static void Main(String[] argv)
27
        {
28

    
29
            Example[] examples = {
30
				new XPathSimple(),
31
				new XPathSimple2(),
32
                new XPathVariables(),
33
                new XPathUndeclaredVariables(),
34
                new XPathWithStaticError(),
35
                new XPathWithDynamicError(),
36
                new XsltSimple1(),
37
                new XsltSimple2(),
38
                new XsltSimple3(),
39
                new XsltStripSpace(),
40
                new XsltReuseExecutable(),
41
                new XsltReuseTransformer(),
42
                new XsltFilterChain(),
43
                new XsltDomToDom(),
44
                new XsltXdmToXdm(),
45
                new XsltXdmElementToXdm(),
46
                new XsltUsingSourceResolver(),
47
                new XsltSettingOutputProperties(),
48
                new XsltDisplayingErrors(),
49
                new XsltCapturingErrors(),
50
                new XsltCapturingMessages(),
51
                new XsltProcessingInstruction(),
52
                new XsltShowingLineNumbers(),
53
                new XsltMultipleOutput(),
54
                new XsltUsingResultHandler(),
55
                new XsltUsingIdFunction(),
56
                new XsltUsingRegisteredCollection(),
57
                new XsltUsingDirectoryCollection(),
58
                new XsltExtensibility(),
59
                new XsltIntegratedExtension(),
60
                new XQueryToStream(),
61
				new XQueryToAtomicValue(),
62
				new XQueryToSequence(),
63
                new XQueryToDom(),
64
				new XQueryToXdm(),
65
                new XQueryCallFunction(),
66
                new XQueryFromXmlReader(),
67
                new XQueryToSerializedSequence(),
68
				new XQueryUsingParameter(),
69
				new XQueryMultiModule(),
70
				new XQueryTryCatch(),
71
				new XQueryExtensibility(),
72
                new XQueryUpdate(),
73
                new XQuerySchemaAware(),
74
                new XPathSchemaAware(),
75
				new XsltStreamDoc(),
76
				new Validate()
77
            };
78

    
79
            Boolean ask = true;
80
            String test = "all";
81

    
82
            String samplesPath = null;
83
            Uri samplesDir;
84

    
85
            foreach (String s in argv)
86
            {
87
                if (s.StartsWith("-test:"))
88
                {
89
                    test = s.Substring(6);
90
                }
91
                else if (s.StartsWith("-dir:"))
92
                {
93
                    samplesPath = s.Substring(5);
94
                }
95
                else if (s == "-ask:yes")
96
                {
97
                    // no action
98
                }
99
                else if (s == "-ask:no")
100
                {
101
                    ask = false;
102
                }
103
                else if (s == "-?")
104
                {
105
                    Console.WriteLine("ExamplesEE -dir:samples -test:testname -ask:yes|no");
106
                }
107
                else
108
                {
109
                    Console.WriteLine("Unrecognized Argument: " + s);
110
                    return;
111
                }
112
            }
113
            if (samplesPath != null)
114
            {
115
                if (samplesPath.StartsWith("file:///"))
116
                {
117
                    samplesPath = samplesPath.Substring(8);
118
                }
119
                else if (samplesPath.StartsWith("file:/"))
120
                {
121
                    samplesPath = samplesPath.Substring(6);
122
                }
123

    
124
            }
125
            else
126
            {
127
                String home = Environment.GetEnvironmentVariable("SAXON_HOME");
128
                if (home == null)
129
                {
130
                    Console.WriteLine("No input directory supplied, and SAXON_HOME is not set");
131
                    return;
132
                }
133
                else
134
                {
135
                    if (!(home.EndsWith("/") || home.EndsWith("\\")))
136
                    {
137
                        home = home + "/";
138
                    }
139
                    samplesPath = home + "samples/";
140
                }
141
            }
142

    
143
            if (!(samplesPath.EndsWith("/") || samplesPath.EndsWith("\\")))
144
            {
145
                samplesPath = samplesPath + "/";
146
            }
147

    
148
            if (!File.Exists(samplesPath + "data/books.xml"))
149
            {
150
                Console.WriteLine("Supplied samples directory " + samplesPath + " does not contain the Saxon sample data files");
151
                return;
152
            }
153

    
154
            try
155
            {
156
                samplesDir = new Uri(samplesPath);
157
            }
158
            catch
159
            {
160
                Console.WriteLine("Invalid URI for samples directory: " + samplesPath);
161
                return;
162
            }
163

    
164
			Boolean found = false;
165
            foreach (Example ex in examples)
166
            {
167
                if (test == "all" || test == ex.testName)
168
                {
169
                    Console.WriteLine("\n\n===== " + ex.testName + " =======\n");
170
					found = true;
171
                    try
172
                    {
173
                        ex.run(samplesDir);
174
                    }
175
                    catch (Saxon.Api.StaticError se)
176
                    {
177
                        Console.WriteLine("Test failed with static error " + se.ErrorCode.LocalName + ": " + se.Message);
178
                    }
179
                    catch (Saxon.Api.DynamicError de)
180
                    {
181
                        Console.WriteLine("Test failed with dynamic error " + de.ErrorCode.LocalName + ": " + de.Message);
182
                    }
183
                    catch (Exception exc)
184
                    {
185
                        Console.WriteLine("Test failed unexpectedly (" + exc.GetType() + "): " + exc.Message);
186
                        Console.WriteLine(exc.StackTrace);
187
                    }
188
                    if (ask)
189
                    {
190
                        Console.WriteLine("\n\nContinue? - type (Y(es)/N(o)/A(ll))");
191
                        String answer = Console.ReadLine();
192
                        if (answer == "N" || answer == "n")
193
                        {
194
                            break;
195
                        }
196
                        else if (answer == "A" || answer == "a")
197
                        {
198
                            ask = false;
199
                        }
200
                    }
201
                }
202
            }
203
			if (!found) {
204
				Console.WriteLine("Please supply a valid test name, or 'all' ('" + test + "' is invalid)");
205
			}
206
            Console.WriteLine("\n==== done! ====");
207
        }
208
    }
209

    
210
    ///<summary>
211
    /// Each of the example programs is implemented as a subclass of the abstract class Example
212
    ///</summary> 
213

    
214

    
215
    public abstract class Example
216
    {
217
        /// <summary>
218
        /// Read-only property: the name of the test example
219
        /// </summary>
220
        public abstract String testName { get; }
221
        /// <summary>
222
        /// Entry point for running the example
223
        /// </summary>
224
        public abstract void run(Uri samplesDir);
225
    }
226

    
227
    /// <summary>
228
	/// Evaluate an XPath expression selecting from a source document supplied as a URI
229
    /// </summary>
230

    
231
    public class XPathSimple : Example
232
    {
233

    
234
        public override String testName
235
        {
236
            get { return "XPathSimple"; }
237
        }
238

    
239
        public override void run(Uri samplesDir)
240
        {
241
            // Create a Processor instance.
242
            Processor processor = new Processor();
243

    
244
            // Load the source document
245
            XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/books.xml"));
246

    
247
            // Create an XPath compiler
248
            XPathCompiler xpath = processor.NewXPathCompiler();
249

    
250
            // Enable caching, so each expression is only compiled once
251
            xpath.Caching = true;
252

    
253
            // Compile and evaluate some XPath expressions
254
            foreach (XdmItem item in xpath.Evaluate("//ITEM", input))
255
            {
256
                Console.WriteLine("TITLE: " + xpath.EvaluateSingle("string(TITLE)", item));
257
                Console.WriteLine("PRICE: " + xpath.EvaluateSingle("string(PRICE)", item));
258
            }
259
        }
260
	}
261

    
262
	/// <summary>
263
	/// Evaluate an XPath expression against a source document, returning its effective boolean value
264
	/// </summary>
265

    
266
	public class XPathSimple2 : Example
267
	{
268

    
269
		public override String testName
270
		{
271
			get { return "XPathSimple2"; }
272
		}
273

    
274
		public override void run(Uri samplesDir)
275
		{
276
			// Create a Processor instance.
277
			Processor processor = new Processor();
278

    
279
			// Load the source document
280
			XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/books.xml"));
281

    
282
			// Create an XPath compiler
283
			XPathCompiler xpath = processor.NewXPathCompiler();
284

    
285
			// Enable caching, so each expression is only compiled once
286
			xpath.Caching = true;
287

    
288
			// Compile and evaluate an XPath expression
289
			XPathSelector selector = xpath.Compile("//ITEM").Load();
290
			selector.ContextItem = input;
291
			Console.WriteLine(selector.EffectiveBooleanValue());
292

    
293
		}
294
	}
295

    
296
    /// <summary>
297
	/// Evaluate an XPath expression using variables (and no source document)
298
    /// </summary>
299

    
300
    public class XPathVariables : Example
301
    {
302

    
303
        public override String testName
304
        {
305
            get { return "XPathVariables"; }
306
        }
307

    
308
        public override void run(Uri samplesDir)
309
        {
310
            // Create a Processor instance.
311
            Processor processor = new Processor();
312

    
313
            // Create the XPath expression.
314
            XPathCompiler compiler = processor.NewXPathCompiler();
315
            compiler.DeclareVariable(new QName("", "a"));
316
            compiler.DeclareVariable(new QName("", "b"));
317
            XPathSelector selector = compiler.Compile("$a + $b").Load();
318

    
319
            // Set the values of the variables
320
            selector.SetVariable(new QName("", "a"), new XdmAtomicValue(2));
321
            selector.SetVariable(new QName("", "b"), new XdmAtomicValue(3));
322

    
323
            // Evaluate the XPath expression
324
            Console.WriteLine(selector.EvaluateSingle().ToString());
325
        }
326
    }
327

    
328
    /// <summary>
329
	/// Evaluate an XPath expression using variables without explicit declaration
330
    /// </summary>
331

    
332
    public class XPathUndeclaredVariables : Example
333
    {
334

    
335
        public override String testName
336
        {
337
            get { return "XPathUndeclaredVariables"; }
338
        }
339

    
340
        public override void run(Uri samplesDir)
341
        {
342
            // Create a Processor instance.
343
            Processor processor = new Processor();
344

    
345
            // Create the XPath expression.
346
            XPathCompiler compiler = processor.NewXPathCompiler();
347
            compiler.AllowUndeclaredVariables = true;
348
            XPathExecutable expression = compiler.Compile("$a + $b");
349
            XPathSelector selector = expression.Load();
350

    
351
            // Set the values of the variables
352
            IEnumerator vars = expression.EnumerateExternalVariables();
353
            while (vars.MoveNext())
354
            {
355
                selector.SetVariable((QName)vars.Current, new XdmAtomicValue(10));
356
            }
357

    
358
            // Evaluate the XPath expression
359
            Console.WriteLine(selector.EvaluateSingle().ToString());
360
        }
361
    }
362

    
363
    /// <summary>
364
	/// Evaluate an XPath expression throwing a static error
365
    /// </summary>
366

    
367
    public class XPathWithStaticError : Example
368
    {
369

    
370
        public override String testName
371
        {
372
            get { return "XPathWithStaticError"; }
373
        }
374

    
375
        public override void run(Uri samplesDir)
376
        {
377
            // Create a Processor instance.
378
            Processor processor = new Processor();
379

    
380
            // Create the XPath expression.
381
            XPathCompiler compiler = processor.NewXPathCompiler();
382
            compiler.AllowUndeclaredVariables = true;
383
            XPathExecutable expression = compiler.Compile("1 + unknown()");
384
            XPathSelector selector = expression.Load();
385

    
386
            // Evaluate the XPath expression
387
            Console.WriteLine(selector.EvaluateSingle().ToString());
388
        }
389
    }
390

    
391
    /// <summary>
392
	/// Evaluate an XPath expression throwing a dynamic error
393
    /// </summary>
394

    
395
    public class XPathWithDynamicError : Example
396
    {
397

    
398
        public override String testName
399
        {
400
            get { return "XPathWithDynamicError"; }
401
        }
402

    
403
        public override void run(Uri samplesDir)
404
        {
405
            // Create a Processor instance.
406
            Processor processor = new Processor();
407

    
408
            // Create the XPath expression.
409
            XPathCompiler compiler = processor.NewXPathCompiler();
410
            compiler.AllowUndeclaredVariables = true;
411
            XPathExecutable expression = compiler.Compile("$a gt $b");
412
            XPathSelector selector = expression.Load();
413

    
414
            // Set the values of the variables
415
            selector.SetVariable(new QName("", "a"), new XdmAtomicValue(10));
416
            selector.SetVariable(new QName("", "b"), new XdmAtomicValue("Paris"));
417

    
418
            // Evaluate the XPath expression
419
            Console.WriteLine(selector.EvaluateSingle().ToString());
420
        }
421
    }
422

    
423
    /// <summary>
424
    /// XSLT 2.0 transformation with source document and stylesheet supplied as URIs
425
    /// </summary>
426

    
427
    public class XsltSimple1 : Example
428
    {
429

    
430
        public override String testName
431
        {
432
            get { return "XsltSimple1"; }
433
        }
434

    
435
        public override void run(Uri samplesDir)
436
        {
437
            // Create a Processor instance.
438
            Processor processor = new Processor();
439

    
440
            // Load the source document
441
            XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/books.xml"));
442

    
443
            // Create a transformer for the stylesheet.
444
            XsltTransformer transformer = processor.NewXsltCompiler().Compile(new Uri(samplesDir, "styles/books.xsl")).Load();
445

    
446
            // Set the root node of the source document to be the initial context node
447
            transformer.InitialContextNode = input;
448

    
449
            // Create a serializer, with output to the standard output stream
450
            Serializer serializer = new Serializer();
451
            serializer.SetOutputWriter(Console.Out);
452

    
453
            // Transform the source XML and serialize the result document
454
            transformer.Run(serializer);
455
        }
456
    }
457

    
458
    /// <summary>
459
    /// Run a transformation, sending the serialized output to a file
460
    /// </summary>
461

    
462
    public class XsltSimple2 : Example
463
    {
464

    
465
        public override String testName
466
        {
467
            get { return "XsltSimple2"; }
468
        }
469

    
470
        public override void run(Uri samplesDir)
471
        {
472
            // Create a Processor instance.
473
            Processor processor = new Processor();
474

    
475
            // Load the source document
476
            XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/books.xml"));
477

    
478
            // Create a transformer for the stylesheet.
479
            XsltTransformer transformer = processor.NewXsltCompiler().Compile(new Uri(samplesDir, "styles/identity.xsl")).Load();
480

    
481
            // Set the root node of the source document to be the initial context node
482
            transformer.InitialContextNode = input;
483

    
484
            // Create a serializer
485
            String outfile = "OutputFromXsltSimple2.xml";
486
            Serializer serializer = new Serializer();
487
            serializer.SetOutputStream(new FileStream(outfile, FileMode.Create, FileAccess.Write));
488

    
489
			// Transform the source XML and serialize the result to the output file.
490
            transformer.Run(serializer);
491

    
492
            Console.WriteLine("\nOutput written to " + outfile + "\n");
493
        }
494
    }
495

    
496
    /// <summary>
497
    /// XSLT 2.0 transformation with source document and stylesheet supplied as files
498
    /// </summary>
499

    
500
    public class XsltSimple3 : Example
501
    {
502

    
503
        public override String testName
504
        {
505
            get { return "XsltSimple3"; }
506
        }
507

    
508
        public override void run(Uri samplesDir)
509
        {
510
            if (samplesDir.Scheme != Uri.UriSchemeFile)
511
            {
512
                Console.WriteLine("Supplied URI must be a file directory");
513
            }
514
            String dir = samplesDir.AbsolutePath;
515
            String sourceFile = dir + "data/books.xml";
516
            String styleFile = dir + "styles/books.xsl";
517

    
518
            // Create a Processor instance.
519
            Processor processor = new Processor();
520

    
521
            // Load the source document
522
            DocumentBuilder builder = processor.NewDocumentBuilder();
523
            builder.BaseUri = new Uri(samplesDir, "data/books.xml");
524

    
525
            XdmNode input = builder.Build(File.OpenRead(sourceFile));
526

    
527
            // Create a transformer for the stylesheet.
528
            XsltCompiler compiler = processor.NewXsltCompiler();
529
            compiler.BaseUri = new Uri(samplesDir, "styles/books.xsl");
530
            XsltTransformer transformer = compiler.Compile(File.OpenRead(styleFile)).Load();
531

    
532
            // Set the root node of the source document to be the initial context node
533
            transformer.InitialContextNode = input;
534

    
535
            // Create a serializer, with output to the standard output stream
536
            Serializer serializer = new Serializer();
537
            serializer.SetOutputWriter(Console.Out);
538

    
539
            // Transform the source XML and serialize the result document
540
            transformer.Run(serializer);
541
        }
542
    }
543

    
544

    
545
    /// <summary>
546
    /// XSLT 2.0 transformation showing stripping of whitespace controlled by the stylesheet
547
    /// </summary>
548

    
549
    public class XsltStripSpace : Example
550
    {
551

    
552
        public override String testName
553
        {
554
            get { return "XsltStripSpace"; }
555
        }
556

    
557
        public override void run(Uri samplesDir)
558
        {
559
            Processor processor = new Processor();
560

    
561
            // Load the source document
562
            DocumentBuilder builder = processor.NewDocumentBuilder();
563
            builder.BaseUri = samplesDir;
564

    
565
            String doc = "<doc>  <a>  <b>text</b>  </a>  <a/>  </doc>";
566
            MemoryStream ms = new MemoryStream();
567
            StreamWriter tw = new StreamWriter(ms);
568
            tw.Write(doc);
569
            tw.Flush();
570
            Stream instr = new MemoryStream(ms.GetBuffer(), 0, (int)ms.Length);
571
            XdmNode input = builder.Build(instr);
572

    
573
            // Create a transformer for the stylesheet.
574
            String stylesheet =
575
                "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0'>" +
576
                "<xsl:strip-space elements='*'/>" +
577
                "<xsl:template match='/'>" +
578
                "  <xsl:copy-of select='.'/>" +
579
                "</xsl:template>" +
580
                "</xsl:stylesheet>";
581

    
582
            XsltCompiler compiler = processor.NewXsltCompiler();
583
            compiler.BaseUri = samplesDir;
584
            XsltTransformer transformer = compiler.Compile(new XmlTextReader(new StringReader(stylesheet))).Load();
585

    
586
            // Set the root node of the source document to be the initial context node
587
            transformer.InitialContextNode = input;
588

    
589
			// Create a serializer, with output to the standard output stream
590
            Serializer serializer = new Serializer();
591
            serializer.SetOutputWriter(Console.Out);
592

    
593
			// Transform the source XML and serialize the result document
594
            transformer.Run(serializer);
595
        }
596
    }
597

    
598

    
599
	/// <summary>
600
	/// Run a transformation, compiling the stylesheet once (into an XsltExecutable) and using it to transform two 
601
	/// different source documents
602
	/// </summary>
603

    
604
    public class XsltReuseExecutable : Example
605
    {
606

    
607
        public override String testName
608
        {
609
            get { return "XsltReuseExecutable"; }
610
        }
611

    
612
        public override void run(Uri samplesDir)
613
        {
614
            // Create a Processor instance.
615
            Processor processor = new Processor();
616

    
617
            // Create a compiled stylesheet
618
            XsltExecutable templates = processor.NewXsltCompiler().Compile(new Uri(samplesDir, "styles/summarize.xsl"));
619

    
620
            // Note: we could actually use the same XsltTransformer in this case.
621
            // But in principle, the two transformations could be done in parallel in separate threads.
622

    
623
            String sourceFile1 = "data/books.xml";
624
            String sourceFile2 = "data/othello.xml";
625

    
626
            // Do the first transformation
627
            Console.WriteLine("\n\n----- transform of " + sourceFile1 + " -----");
628
            XsltTransformer transformer1 = templates.Load();
629
            transformer1.InitialContextNode = processor.NewDocumentBuilder().Build(new Uri(samplesDir, sourceFile1));
630
            transformer1.Run(new Serializer());     // default destination is Console.Out
631

    
632
            // Do the second transformation
633
            Console.WriteLine("\n\n----- transform of " + sourceFile2 + " -----");
634
            XsltTransformer transformer2 = templates.Load();
635
            transformer2.InitialContextNode = processor.NewDocumentBuilder().Build(new Uri(samplesDir, sourceFile2));
636
            transformer2.Run(new Serializer());     // default destination is Console.Out    
637
        }
638
    }
639

    
640
    /// <summary>
641
    /// Show that the XsltTransformer is serially reusable; run a transformation twice using the same stylesheet
642
    /// and the same input document but with different parameters.
643
    /// </summary>
644

    
645
    public class XsltReuseTransformer : Example
646
    {
647

    
648
        public override String testName
649
        {
650
            get { return "XsltReuseTransformer"; }
651
        }
652

    
653
        public override void run(Uri samplesDir)
654
        {
655
            // Create a Processor instance.
656
            Processor processor = new Processor();
657

    
658
            // Load the source document, building a tree
659
            XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/books.xml"));
660

    
661
            // Compile the stylesheet
662
            XsltExecutable exec = processor.NewXsltCompiler().Compile(new Uri(samplesDir, "styles/summarize.xsl"));
663

    
664
            // Create a transformer 
665
            XsltTransformer transformer = exec.Load();
666

    
667
            // Run it once        
668
            transformer.SetParameter(new QName("", "", "include-attributes"), new XdmAtomicValue(false));
669
            transformer.InitialContextNode = input;
670
            XdmDestination results = new XdmDestination();
671
            transformer.Run(results);
672
            Console.WriteLine("1: " + results.XdmNode.OuterXml);
673

    
674
            // Run it again        
675
            transformer.SetParameter(new QName("", "", "include-attributes"), new XdmAtomicValue(true));
676
            transformer.InitialContextNode = input;
677
            results.Reset();
678
            transformer.Run(results);
679
            Console.WriteLine("2: " + results.XdmNode.OuterXml);
680
        }
681
    }
682

    
683
    /// <summary>
684
    /// Run a sequence of transformations in a pipeline, each one acting as a filter
685
    /// </summary>
686

    
687
    public class XsltFilterChain : Example
688
    {
689

    
690
        public override String testName
691
        {
692
            get { return "XsltFilterChain"; }
693
        }
694

    
695
        public override void run(Uri samplesDir)
696
        {
697
            // Create a Processor instance.
698
            Processor processor = new Processor();
699

    
700
            // Load the source document
701
            XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/books.xml"));
702

    
703
            // Create a compiler
704
            XsltCompiler compiler = processor.NewXsltCompiler();
705

    
706
            // Compile all three stylesheets
707
            XsltTransformer transformer1 = compiler.Compile(new Uri(samplesDir, "styles/identity.xsl")).Load();
708
            XsltTransformer transformer2 = compiler.Compile(new Uri(samplesDir, "styles/books.xsl")).Load();
709
            XsltTransformer transformer3 = compiler.Compile(new Uri(samplesDir, "styles/summarize.xsl")).Load();
710

    
711
            // Now run them in series
712
            transformer1.InitialContextNode = input;
713
            XdmDestination results1 = new XdmDestination();
714
            transformer1.Run(results1);
715
            //Console.WriteLine("After phase 1:");
716
            //Console.WriteLine(results1.XdmNode.OuterXml);
717

    
718
            transformer2.InitialContextNode = results1.XdmNode;
719
            XdmDestination results2 = new XdmDestination();
720
            transformer2.Run(results2);
721
            //Console.WriteLine("After phase 2:");
722
            //Console.WriteLine(results2.XdmNode.OuterXml);
723

    
724
            transformer3.InitialContextNode = results2.XdmNode;
725
            XdmDestination results3 = new XdmDestination();
726
            transformer3.Run(results3);
727
            Console.WriteLine("After phase 3:");
728
            Console.WriteLine(results3.XdmNode.OuterXml);
729
        }
730
    }
731

    
732
    /// <summary>
733
    /// Transform from an XDM tree to an XDM tree
734
    /// </summary>
735

    
736
    public class XsltXdmToXdm : Example
737
    {
738

    
739
        public override String testName
740
        {
741
            get { return "XsltXdmToXdm"; }
742
        }
743

    
744
        public override void run(Uri samplesDir)
745
        {
746
            // Create a Processor instance.
747
            Processor processor = new Processor();
748

    
749
            // Load the source document
750
            XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/books.xml"));
751

    
752
            // Create a compiler
753
            XsltCompiler compiler = processor.NewXsltCompiler();
754

    
755
            // Compile the stylesheet
756
            XsltTransformer transformer = compiler.Compile(new Uri(samplesDir, "styles/summarize.xsl")).Load();
757

    
758
            // Run the transformation
759
            transformer.InitialContextNode = input;
760
            XdmDestination result = new XdmDestination();
761
            transformer.Run(result);
762

    
763
            // Serialize the result so we can see that it worked
764
            StringWriter sw = new StringWriter();
765
            result.XdmNode.WriteTo(new XmlTextWriter(sw));
766
            Console.WriteLine(sw.ToString());
767

    
768
            // Note: we don't do 
769
            //   result.XdmNode.WriteTo(new XmlTextWriter(Console.Out));
770
            // because that results in the Console.out stream being closed, 
771
            // with subsequent attempts to write to it being rejected.
772
        }
773
    }
774

    
775
    /// <summary>
776
    /// Run an XSLT transformation from an Xdm tree, starting at a node that is not the document node
777
    /// </summary>
778

    
779
    public class XsltXdmElementToXdm : Example
780
    {
781

    
782
        public override String testName
783
        {
784
            get { return "XsltXdmElementToXdm"; }
785
        }
786

    
787
        public override void run(Uri samplesDir)
788
        {
789
            // Create a Processor instance.
790
            Processor processor = new Processor();
791

    
792
            // Load the source document
793
            XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/othello.xml"));
794

    
795
            // Navigate to the first grandchild
796
            XPathSelector eval = processor.NewXPathCompiler().Compile("/PLAY/FM[1]").Load();
797
            eval.ContextItem = input;
798
            input = (XdmNode)eval.EvaluateSingle();
799

    
800
            // Create an XSLT compiler
801
            XsltCompiler compiler = processor.NewXsltCompiler();
802

    
803
            // Compile the stylesheet
804
            XsltTransformer transformer = compiler.Compile(new Uri(samplesDir, "styles/summarize.xsl")).Load();
805

    
806
            // Run the transformation
807
            transformer.InitialContextNode = input;
808
            XdmDestination result = new XdmDestination();
809
            transformer.Run(result);
810

    
811
            // Serialize the result so we can see that it worked
812
            Console.WriteLine(result.XdmNode.OuterXml);
813
        }
814
    }
815

    
816
    /// <summary>
817
    /// Run a transformation from a DOM (System.Xml.Document) input to a DOM output
818
    /// </summary>
819

    
820
    public class XsltDomToDom : Example
821
    {
822

    
823
        public override String testName
824
        {
825
            get { return "XsltDomToDom"; }
826
        }
827

    
828
        public override void run(Uri samplesDir)
829
        {
830
            // Create a Processor instance.
831
            Processor processor = new Processor();
832

    
833
            // Load the source document (in practice, it would already exist as a DOM)
834
            XmlDocument doc = new XmlDocument();
835
            doc.Load(new XmlTextReader(samplesDir.AbsolutePath + "data/othello.xml"));
836
            XdmNode input = processor.NewDocumentBuilder().Wrap(doc);
837

    
838
            // Create a compiler
839
            XsltCompiler compiler = processor.NewXsltCompiler();
840

    
841
            // Compile the stylesheet
842
            XsltTransformer transformer = compiler.Compile(new Uri(samplesDir, "styles/summarize.xsl")).Load();
843

    
844
            // Run the transformation
845
            transformer.InitialContextNode = input;
846
            DomDestination result = new DomDestination();
847
            transformer.Run(result);
848

    
849
            // Serialize the result so we can see that it worked
850
            Console.WriteLine(result.XmlDocument.OuterXml);
851
        }
852
    }
853

    
854

    
855
    /// <summary>
856
    /// Run a transformation driven by an xml-stylesheet processing instruction in the source document
857
    /// </summary>
858

    
859
    public class XsltProcessingInstruction : Example
860
    {
861

    
862
        public override string testName
863
        {
864
            get { return "XsltProcessingInstruction"; }
865
        }
866

    
867
        public override void run(Uri samplesDir)
868
        {
869
            // Create a Processor instance.
870
            Processor processor = new Processor();
871
            XsltExecutable exec;
872

    
873
            // Load the source document
874
            XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/books.xml"));
875
            //Console.WriteLine("=============== source document ===============");
876
            //Console.WriteLine(input.OuterXml);
877
            //Console.WriteLine("=========== end of source document ============");
878

    
879
            // Navigate to the xml-stylesheet processing instruction having the pseudo-attribute type=text/xsl;
880
            // then extract the value of the href pseudo-attribute if present
881

    
882
            String path = @"/processing-instruction(xml-stylesheet)[matches(.,'type\s*=\s*[''""]text/xsl[''""]')]" +
883
                    @"/replace(., '.*?href\s*=\s*[''""](.*?)[''""].*', '$1')";
884

    
885
            XPathSelector eval = processor.NewXPathCompiler().Compile(path).Load();
886
            eval.ContextItem = input;
887
            XdmAtomicValue hrefval = (XdmAtomicValue)eval.EvaluateSingle();
888
            String href = (hrefval == null ? null : hrefval.ToString());
889

    
890
            if (href == null || href == "")
891
            {
892
                Console.WriteLine("No suitable xml-stylesheet processing instruction found");
893
                return;
894

    
895
            }
896
            else if (href[0] == '#')
897
            {
898

    
899
                // The stylesheet is embedded in the source document and identified by a URI of the form "#id"
900

    
901
                Console.WriteLine("Locating embedded stylesheet with href = " + href);
902
                String idpath = "id('" + href.Substring(1) + "')";
903
                eval = processor.NewXPathCompiler().Compile(idpath).Load();
904
                eval.ContextItem = input;
905
                XdmNode node = (XdmNode)eval.EvaluateSingle();
906
                if (node == null)
907
                {
908
                    Console.WriteLine("No element found with ID " + href.Substring(1));
909
                    return;
910
                }
911
                exec = processor.NewXsltCompiler().Compile(node);
912

    
913
            }
914
            else
915
            {
916

    
917
                // The stylesheet is in an external document
918

    
919
                Console.WriteLine("Locating stylesheet at uri = " + new Uri(input.BaseUri, href));
920

    
921
                // Fetch and compile the referenced stylesheet
922
                exec = processor.NewXsltCompiler().Compile(new Uri(input.BaseUri, href.ToString()));
923
            }
924

    
925
            // Create a transformer 
926
            XsltTransformer transformer = exec.Load();
927

    
928
            // Run it       
929
            transformer.InitialContextNode = input;
930
            XdmDestination results = new XdmDestination();
931
            transformer.Run(results);
932
            Console.WriteLine(results.XdmNode.OuterXml);
933

    
934
        }
935
    }
936

    
937
    /// <summary>
938
    /// Run an XSLT transformation setting serialization properties from the calling application
939
    /// </summary>
940

    
941
    public class XsltSettingOutputProperties : Example
942
    {
943

    
944
        public override string testName
945
        {
946
            get { return "XsltSettingOutputProperties"; }
947
        }
948

    
949
        public override void run(Uri samplesDir)
950
        {
951
            // Create a Processor instance.
952
            Processor processor = new Processor();
953

    
954
            // Load the source document
955
            XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/books.xml"));
956

    
957
            // Create a transformer for the stylesheet.
958
            XsltTransformer transformer = processor.NewXsltCompiler().Compile(new Uri(samplesDir, "styles/summarize.xsl")).Load();
959

    
960
            // Set the root node of the source document to be the initial context node
961
            transformer.InitialContextNode = input;
962

    
963
            // Create a serializer, with output to the standard output stream
964
            Serializer serializer = new Serializer();
965
            serializer.SetOutputProperty(Serializer.METHOD, "xml");
966
            serializer.SetOutputProperty(Serializer.INDENT, "no");
967
            serializer.SetOutputWriter(Console.Out);
968

    
969
            // Transform the source XML and serialize the result document
970
            transformer.Run(serializer);
971
        }
972

    
973
    }
974

    
975
    /// <summary>
976
    /// Run an XSLT transformation making use of an XmlResolver to resolve URIs at document build time, at stylesheet compile time 
977
    /// and at transformation run-time
978
    /// </summary>
979

    
980
    public class XsltUsingSourceResolver : Example
981
    {
982

    
983
        public override string testName
984
        {
985
            get { return "XsltUsingSourceResolver"; }
986
        }
987

    
988
        public override void run(Uri samplesDir)
989
        {
990

    
991
            // Create a Processor instance.
992
            Processor processor = new Processor();
993

    
994
            // Load the source document
995
            DocumentBuilder builder = processor.NewDocumentBuilder();
996
            UserXmlResolver buildTimeResolver = new UserXmlResolver();
997
            buildTimeResolver.Message = "** Calling build-time XmlResolver: ";
998
            builder.XmlResolver = buildTimeResolver;
999
            builder.BaseUri = samplesDir;
1000

    
1001
            String doc = "<!DOCTYPE doc [<!ENTITY e SYSTEM 'flamingo.txt'>]><doc>&e;</doc>";
1002
            MemoryStream ms = new MemoryStream();
1003
            StreamWriter tw = new StreamWriter(ms);
1004
            tw.Write(doc);
1005
            tw.Flush();
1006
            Stream instr = new MemoryStream(ms.GetBuffer(), 0, (int)ms.Length);
1007
            XdmNode input = builder.Build(instr);
1008

    
1009
            // Create a transformer for the stylesheet.
1010
            String stylesheet =
1011
                "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0'>" +
1012
                "<xsl:import href='empty.xslt'/>" +
1013
                "<xsl:template match='/'>" +
1014
                "<out note=\"{doc('heron.txt')}\" ><xsl:copy-of select='.'/></out>" +
1015
                "</xsl:template>" +
1016
                "</xsl:stylesheet>";
1017

    
1018
            XsltCompiler compiler = processor.NewXsltCompiler();
1019
            UserXmlResolver compileTimeResolver = new UserXmlResolver();
1020
            compileTimeResolver.Message = "** Calling compile-time XmlResolver: ";
1021
            compiler.XmlResolver = compileTimeResolver;
1022
            compiler.BaseUri = samplesDir;
1023
            XsltTransformer transformer = compiler.Compile(new XmlTextReader(new StringReader(stylesheet))).Load();
1024

    
1025
            // Set the root node of the source document to be the initial context node
1026
            transformer.InitialContextNode = input;
1027

    
1028
            // Set the user-written XmlResolver
1029
            UserXmlResolver runTimeResolver = new UserXmlResolver();
1030
            runTimeResolver.Message = "** Calling transformation-time XmlResolver: ";
1031
            transformer.InputXmlResolver = runTimeResolver;
1032

    
1033
            // Create a serializer
1034
            Serializer serializer = new Serializer();
1035
            serializer.SetOutputWriter(Console.Out);
1036

    
1037
			// Transform the source XML and serialize the result document
1038
            transformer.Run(serializer);
1039

    
1040
        }
1041
    }
1042

    
1043
    /// <summary>
1044
    /// Run an XSLT transformation displaying compile-time errors to the console
1045
    /// </summary>
1046

    
1047
    public class XsltDisplayingErrors : Example
1048
    {
1049

    
1050
        public override string testName
1051
        {
1052
            get { return "XsltDisplayingErrors"; }
1053
        }
1054

    
1055
        public override void run(Uri samplesDir)
1056
        {
1057
            // Create a Processor instance.
1058
            Processor processor = new Processor();
1059

    
1060
            // Create the XSLT Compiler
1061
            XsltCompiler compiler = processor.NewXsltCompiler();
1062

    
1063

    
1064
            // Define a stylesheet containing errors
1065
            String stylesheet =
1066
                "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0'>\n" +
1067
                "<xsl:template name='eee:template'>\n" +
1068
                "  <xsl:value-of select='32'/>\n" +
1069
                "</xsl:template>\n" +
1070
                "<xsl:template name='main'>\n" +
1071
                "  <xsl:value-of select='$var'/>\n" +
1072
                "</xsl:template>\n" +
1073
                "</xsl:stylesheet>";
1074

    
1075

    
1076
            // Attempt to compile the stylesheet and display the errors
1077
            try
1078
            {
1079
                compiler.BaseUri = new Uri("http://localhost/stylesheet");
1080
                compiler.Compile(new XmlTextReader(new StringReader(stylesheet)));
1081
                Console.WriteLine("Stylesheet compilation succeeded");
1082
            }
1083
            catch (Exception)
1084
            {
1085
                Console.WriteLine("Stylesheet compilation failed");
1086
            }
1087

    
1088

    
1089
        }
1090
    }
1091

    
1092
    /// <summary>
1093
    /// Run an XSLT transformation capturing compile-time errors within the application
1094
    /// </summary>
1095

    
1096
    public class XsltCapturingErrors : Example
1097
    {
1098

    
1099
        public override string testName
1100
        {
1101
            get { return "XsltCapturingErrors"; }
1102
        }
1103

    
1104
        public override void run(Uri samplesDir)
1105
        {
1106
            // Create a Processor instance.
1107
            Processor processor = new Processor();
1108

    
1109
            // Create the XSLT Compiler
1110
            XsltCompiler compiler = processor.NewXsltCompiler();
1111

    
1112
            // Create a list to hold the error information
1113
            compiler.ErrorList = new ArrayList();
1114

    
1115
            // Define a stylesheet containing errors
1116
            String stylesheet =
1117
                "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0'>\n" +
1118
                "<xsl:template name='fff:template'>\n" +
1119
                "  <xsl:value-of select='32'/>\n" +
1120
                "</xsl:template>\n" +
1121
                "<xsl:template name='main'>\n" +
1122
                "  <xsl:value-of select='$var'/>\n" +
1123
                "</xsl:template>\n" +
1124
                "</xsl:stylesheet>";
1125

    
1126

    
1127
            // Attempt to compile the stylesheet and display the errors
1128
            try
1129
            {
1130
                compiler.BaseUri = new Uri("http://localhost/stylesheet");
1131
                compiler.Compile(new StringReader(stylesheet));
1132
                Console.WriteLine("Stylesheet compilation succeeded");
1133
            }
1134
            catch (Exception)
1135
            {
1136
                Console.WriteLine("Stylesheet compilation failed with " + compiler.ErrorList.Count + " errors");
1137
                foreach (StaticError error in compiler.ErrorList)
1138
                {
1139
                    Console.WriteLine("At line " + error.LineNumber + ": " + error.Message);
1140
                }
1141
            }
1142
        }
1143
    }
1144

    
1145
    /// <summary>
1146
    /// Run an XSLT transformation capturing run-time messages within the application
1147
    /// </summary>
1148

    
1149
    public class XsltCapturingMessages : Example
1150
    {
1151

    
1152
        public override string testName
1153
        {
1154
            get { return "XsltCapturingMessages"; }
1155
        }
1156

    
1157
        public override void run(Uri samplesDir)
1158
        {
1159

    
1160
            // Create a Processor instance.
1161
            Processor processor = new Processor();
1162

    
1163
            // Create the XSLT Compiler
1164
            XsltCompiler compiler = processor.NewXsltCompiler();
1165

    
1166
            // Define a stylesheet that generates messages
1167
            String stylesheet =
1168
                "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0'>\n" +
1169
                "<xsl:template name='main'>\n" +
1170
                "  <xsl:message><a>starting</a></xsl:message>\n" +
1171
                "  <out><xsl:value-of select='current-date()'/></out>\n" +
1172
                "  <xsl:message><a>finishing</a></xsl:message>\n" +
1173
                "</xsl:template>\n" +
1174
                "</xsl:stylesheet>";
1175

    
1176
            compiler.BaseUri = new Uri("http://localhost/stylesheet");
1177
            XsltExecutable exec = compiler.Compile(new StringReader(stylesheet));
1178

    
1179

    
1180
            // Create a transformer for the stylesheet.
1181
            XsltTransformer transformer = exec.Load();
1182

    
1183
            // Set the name of the initial template
1184
            transformer.InitialTemplate = new QName("", "main");
1185

    
1186
            // Create a Listener to which messages will be written
1187
            transformer.MessageListener = new UserMessageListener();
1188

    
1189
			// Create a serializer, with output to the standard output stream
1190
            Serializer serializer = new Serializer();
1191
            serializer.SetOutputWriter(Console.Out);
1192

    
1193
			// Transform the source XML and serialize the result document
1194
            transformer.Run(serializer);
1195
        }
1196

    
1197
    }
1198

    
1199
    ///
1200
    /// Example user-written message listener
1201
    ///
1202

    
1203
    public class UserMessageListener : IMessageListener
1204
    {
1205

    
1206
        public void Message(XdmNode content, bool terminate, IXmlLocation location)
1207
        {
1208
            Console.Out.WriteLine("MESSAGE terminate=" + (terminate ? "yes" : "no") + " at " + DateTime.Now);
1209
            Console.Out.WriteLine("From instruction at line " + location.LineNumber +
1210
                    " of " + location.BaseUri);
1211
            Console.Out.WriteLine(">>" + content.StringValue);
1212
        }
1213
    }
1214

    
1215

    
1216
    /// <summary>
1217
    /// Run an XSLT transformation showing source line numbers
1218
    /// </summary>
1219

    
1220
    public class XsltShowingLineNumbers : Example
1221
    {
1222

    
1223
        public override string testName
1224
        {
1225
            get { return "XsltShowingLineNumbers"; }
1226
        }
1227

    
1228
        public override void run(Uri samplesDir)
1229
        {
1230

    
1231
            // Create a Processor instance.
1232
            Processor processor = new Processor(true);
1233

    
1234
            // Ask for the JAXP parser to be used (or not to be used, if false)
1235
            processor.SetProperty("http://saxon.sf.net/feature/preferJaxpParser", "false");
1236

    
1237
            // Load the source document
1238
            DocumentBuilder builder = processor.NewDocumentBuilder();
1239
            builder.IsLineNumbering = true;
1240
            XdmNode input = builder.Build(new Uri(samplesDir, "data/othello.xml"));
1241

    
1242
            // Create the XSLT Compiler
1243
            XsltCompiler compiler = processor.NewXsltCompiler();
1244

    
1245
            // Define a stylesheet that shows line numbers of source elements
1246
            String stylesheet =
1247
                "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0' xmlns:saxon='http://saxon.sf.net/'>\n" +
1248
                "<xsl:template match='/'>\n" +
1249
                "<out>\n" +
1250
                "  <xsl:for-each select='//ACT'>\n" +
1251
                "  <out><xsl:value-of select='saxon:line-number(.)'/></out>\n" +
1252
                "  </xsl:for-each>\n" +
1253
                "</out>\n" +
1254
                "</xsl:template>\n" +
1255
                "</xsl:stylesheet>";
1256

    
1257
            compiler.BaseUri = new Uri("http://localhost/stylesheet");
1258
            XsltExecutable exec = compiler.Compile(new StringReader(stylesheet));
1259

    
1260

    
1261
            // Create a transformer for the stylesheet.
1262
            XsltTransformer transformer = exec.Load();
1263

    
1264
            // Set the root node of the source document to be the initial context node
1265
            transformer.InitialContextNode = input;
1266

    
1267
			// Create a serializer, with output to the standard output stream
1268
            Serializer serializer = new Serializer();
1269
            serializer.SetOutputWriter(Console.Out);
1270

    
1271
			// Transform the source XML and serialize the result document
1272
            transformer.Run(serializer);
1273
        }
1274

    
1275
    }
1276

    
1277
    /// <summary>
1278
    /// Run an XSLT transformation producing multiple output documents
1279
    /// </summary>
1280

    
1281
    public class XsltMultipleOutput : Example
1282
    {
1283

    
1284
        public override string testName
1285
        {
1286
            get { return "XsltMultipleOutput"; }
1287
        }
1288

    
1289
        public override void run(Uri samplesDir)
1290
        {
1291
            // Create a Processor instance.
1292
            Processor processor = new Processor();
1293
            processor.SetProperty("http://saxon.sf.net/feature/timing", "true");
1294

    
1295
            // Load the source document
1296
            XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/othello.xml"));
1297

    
1298
            // Create a transformer for the stylesheet.
1299
            XsltTransformer transformer = processor.NewXsltCompiler().Compile(new Uri(samplesDir, "styles/play.xsl")).Load();
1300

    
1301
            // Set the root node of the source document to be the initial context node
1302
            transformer.InitialContextNode = input;
1303

    
1304
            // Set the required stylesheet parameter
1305
            transformer.SetParameter(new QName("", "", "dir"), new XdmAtomicValue(samplesDir.ToString() + "play"));
1306

    
1307
			// Create a serializer, with output to the standard output stream
1308
            Serializer serializer = new Serializer();
1309
            serializer.SetOutputWriter(Console.Out);
1310

    
1311
			// Transform the source XML and serialize the result document
1312
            transformer.Run(serializer);
1313

    
1314
        }
1315

    
1316
    }
1317

    
1318

    
1319
    /// <summary>
1320
    /// Run an XSLT transformation using the id() function, with DTD validation
1321
    /// </summary>
1322

    
1323
    public class XsltUsingIdFunction : Example
1324
    {
1325

    
1326
        public override string testName
1327
        {
1328
            get { return "XsltUsingIdFunction"; }
1329
        }
1330

    
1331
        public override void run(Uri samplesDir)
1332
        {
1333
            // Create a Processor instance
1334
            Processor processor = new Processor();
1335

    
1336
            // Load the source document. The Microsoft .NET parser does not report attributes of type ID. The only
1337
            // way to use the function is therefore (a) to use a different parser, or (b) to use xml:id instead. We
1338
            // choose the latter course.
1339

    
1340
            String doc = "<!DOCTYPE table [" +
1341
                "<!ELEMENT table (row*)>" +
1342
                "<!ELEMENT row EMPTY>" +
1343
                "<!ATTLIST row xml:id ID #REQUIRED>" +
1344
                "<!ATTLIST row value CDATA #REQUIRED>]>" +
1345
                "<table><row xml:id='A123' value='green'/><row xml:id='Z789' value='blue'/></table>";
1346

    
1347
            DocumentBuilder builder = processor.NewDocumentBuilder();
1348
            builder.DtdValidation = true;
1349
            builder.BaseUri = samplesDir;
1350
            MemoryStream ms = new MemoryStream();
1351
            StreamWriter tw = new StreamWriter(ms);
1352
            tw.Write(doc);
1353
            tw.Flush();
1354
            Stream instr = new MemoryStream(ms.GetBuffer(), 0, (int)ms.Length);
1355
            XdmNode input = builder.Build(instr);
1356

    
1357
            // Define a stylesheet that uses the id() function
1358
            String stylesheet =
1359
                "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0'>\n" +
1360
                "<xsl:template match='/'>\n" +
1361
                "  <xsl:copy-of select=\"id('Z789')\"/>\n" +
1362
                "</xsl:template>\n" +
1363
                "</xsl:stylesheet>";
1364

    
1365
            XsltCompiler compiler = processor.NewXsltCompiler();
1366
            compiler.BaseUri = new Uri("http://localhost/stylesheet");
1367
            XsltExecutable exec = compiler.Compile(new StringReader(stylesheet));
1368

    
1369
            // Create a transformer for the stylesheet
1370
            XsltTransformer transformer = exec.Load();
1371

    
1372
            // Set the root node of the source document to be the initial context node
1373
            transformer.InitialContextNode = input;
1374

    
1375
            // Set the destination
1376
            XdmDestination results = new XdmDestination();
1377

    
1378
            // Transform the XML
1379
            transformer.Run(results);
1380

    
1381
            // Show the result
1382
            Console.WriteLine(results.XdmNode.ToString());
1383

    
1384
        }
1385

    
1386
    }
1387

    
1388
    /// <summary>
1389
    /// Show a transformation using a user-written result document handler. This example
1390
    /// captures each of the result documents in a DOM, and creates a Hashtable that indexes
1391
    /// the DOM trees according to their absolute URI. On completion, it writes all the DOMs
1392
    /// to the standard output.
1393
    /// </summary>
1394

    
1395
    public class XsltUsingResultHandler : Example
1396
    {
1397

    
1398
        public override string testName
1399
        {
1400
            get { return "XsltUsingResultHandler"; }
1401
        }
1402

    
1403
        public override void run(Uri samplesDir)
1404
        {
1405
            // Create a Processor instance.
1406
            Processor processor = new Processor();
1407

    
1408
            // Load the source document
1409
            XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/othello.xml"));
1410

    
1411
            // Define a stylesheet that splits the document up
1412
            String stylesheet =
1413
                "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0'>\n" +
1414
                "<xsl:template match='/'>\n" +
1415
                "  <xsl:for-each select='//ACT'>\n" +
1416
                "    <xsl:result-document href='{position()}.xml'>\n" +
1417
                "      <xsl:copy-of select='TITLE'/>\n" +
1418
                "    </xsl:result-document>\n" +
1419
                "  </xsl:for-each>\n" +
1420
                "</xsl:template>\n" +
1421
                "</xsl:stylesheet>";
1422

    
1423
            XsltCompiler compiler = processor.NewXsltCompiler();
1424
            compiler.BaseUri = new Uri("http://localhost/stylesheet");
1425
            XsltExecutable exec = compiler.Compile(new StringReader(stylesheet));
1426

    
1427
            // Create a transformer for the stylesheet.
1428
            XsltTransformer transformer = exec.Load();
1429

    
1430
            // Set the root node of the source document to be the initial context node
1431
            transformer.InitialContextNode = input;
1432

    
1433
            // Establish the result document handler
1434
            Hashtable results = new Hashtable();
1435
            transformer.ResultDocumentHandler = new UserResultDocumentHandler(results);
1436

    
1437
            // Transform the source XML to a NullDestination (because we only want the secondary result files).
1438
            transformer.Run(new NullDestination());
1439

    
1440
            // Process the captured DOM results
1441
            foreach (DictionaryEntry entry in results)
1442
            {
1443
                string uri = (string)entry.Key;
1444
                Console.WriteLine("\nResult File " + uri);
1445
                DomDestination dom = (DomDestination)results[uri];
1446
                Console.Write(dom.XmlDocument.OuterXml);
1447
            }
1448

    
1449
        }
1450

    
1451
    }
1452

    
1453
    /// <summary>
1454
    /// Show a transformation using a registered collection
1455
    /// </summary>
1456

    
1457
    public class XsltUsingRegisteredCollection : Example
1458
    {
1459

    
1460
        public override string testName
1461
        {
1462
            get { return "XsltUsingRegisteredCollection"; }
1463
        }
1464

    
1465
        public override void run(Uri samplesDir)
1466
        {
1467
            // Create a Processor instance.
1468
            Processor processor = new Processor();
1469

    
1470
			// Define a stylesheet that uses the collection() function
1471
            String stylesheet =
1472
                "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0'>\n" +
1473
                "<xsl:template name='main'>\n" +
1474
                " <out>\n" +
1475
                "  <xsl:for-each select=\"collection('http://www.example.org/my-collection')\">\n" +
1476
                "    <document uri='{document-uri(.)}' nodes='{count(//*)}'/>\n" +
1477
                "  </xsl:for-each><zzz/>\n" +
1478
                "  <xsl:for-each select=\"collection('http://www.example.org/my-collection')\">\n" +
1479
                "    <document uri='{document-uri(.)}' nodes='{count(//*)}'/>\n" +
1480
                "  </xsl:for-each>\n" +
1481
                " </out>\n" +
1482
                "</xsl:template>\n" +
1483
                "</xsl:stylesheet>";
1484

    
1485
			// Register a named collection
1486
            Uri[] documentList = new Uri[2];
1487
            documentList[0] = new Uri(samplesDir, "data/othello.xml");
1488
            documentList[1] = new Uri(samplesDir, "data/books.xml");
1489
            processor.RegisterCollection(new Uri("http://www.example.org/my-collection"), documentList);
1490

    
1491
            XsltCompiler compiler = processor.NewXsltCompiler();
1492
            compiler.BaseUri = new Uri("http://localhost/stylesheet");
1493
            XsltExecutable exec = compiler.Compile(new StringReader(stylesheet));
1494

    
1495
            // Create a transformer for the stylesheet.
1496
            XsltTransformer transformer = exec.Load();
1497

    
1498
			// Set the name of the initial template
1499
            transformer.InitialTemplate = new QName("", "main");
1500

    
1501
            // Set the destination
1502
            XdmDestination results = new XdmDestination();
1503

    
1504
            // Transform the XML
1505
            transformer.Run(results);
1506

    
1507
            // Show the result
1508
            Console.WriteLine(results.XdmNode.ToString());
1509

    
1510
        }
1511
    }
1512

    
1513
    /// <summary>
1514
	/// Show a transformation using a collection that maps to a directory
1515
    /// </summary>
1516

    
1517
    public class XsltUsingDirectoryCollection : Example
1518
    {
1519

    
1520
        public override string testName
1521
        {
1522
            get { return "XsltUsingDirectoryCollection"; }
1523
        }
1524

    
1525
        public override void run(Uri samplesDir)
1526
        {
1527
            // Create a Processor instance.
1528
            Processor processor = new Processor();
1529

    
1530
			// Define a stylesheet that uses the collection() function
1531
            String stylesheet =
1532
                "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0'>\n" +
1533
                "<xsl:template name='main'>\n" +
1534
                " <out>\n" +
1535
                "  <xsl:for-each select=\"collection('" + samplesDir + "?recurse=yes;select=*.xml;on-error=warning')\">\n" +
1536
                "    <document uri='{document-uri(.)}' nodes='{count(//*)}'/>\n" +
1537
                "  </xsl:for-each><zzz/>\n" +
1538
                " </out>\n" +
1539
                "</xsl:template>\n" +
1540
                "</xsl:stylesheet>";
1541

    
1542

    
1543
            XsltCompiler compiler = processor.NewXsltCompiler();
1544
            compiler.BaseUri = new Uri("http://localhost/stylesheet");
1545
            XsltExecutable exec = compiler.Compile(new StringReader(stylesheet));
1546

    
1547
            // Create a transformer for the stylesheet.
1548
            XsltTransformer transformer = exec.Load();
1549

    
1550
			// Set the name of the initial template
1551
            transformer.InitialTemplate = new QName("", "main");
1552

    
1553
            // Set the destination
1554
            XdmDestination results = new XdmDestination();
1555

    
1556
            // Transform the XML
1557
            transformer.Run(results);
1558

    
1559
            // Show the result
1560
            Console.WriteLine(results.XdmNode.ToString());
1561

    
1562
        }
1563

    
1564
    }
1565

    
1566
	/// <summary>
1567
	/// Demonstrate XSLT extensibility using user-written extension functions
1568
	/// </summary>
1569
	/// <remarks>Note: If SamplesExtensions is compiled to a different assembly than ExamplesEE, use 
1570
	/// the namespace URI clitype:SampleExtensions.SampleExtensions?asm=ASSEMBLY_NAME_HERE
1571
	/// </remarks>
1572

    
1573
    public class XsltExtensibility : Example
1574
    {
1575

    
1576
        public override string testName
1577
        {
1578
            get { return "XsltExtensibility"; }
1579
        }
1580

    
1581
        public override void run(Uri samplesDir)
1582
        {
1583
            // Create a Processor instance.
1584
            Processor processor = new Processor(true);
1585

    
1586
            // Identify the Processor version
1587
            Console.WriteLine(processor.ProductVersion);
1588

    
1589
            // Set diagnostics
1590
            //processor.SetProperty("http://saxon.sf.net/feature/trace-external-functions", "true");
1591

    
1592
            // Create the stylesheet
1593
            String s = @"<xsl:transform version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'" +
1594
                @" xmlns:ext='clitype:SampleExtensions.SampleExtensions?asm=ExamplesEE' " +
1595
                @" xmlns:tz='clitype:System.TimeZone' " +
1596
                @" xmlns:math='http://example.math.co.uk/demo' " +
1597
                @" xmlns:env='http://example.env.co.uk/demo' " +
1598
                @" exclude-result-prefixes='ext math env tz'> " +
1599
                @" <xsl:param name='timezone' required='yes'/> " +
1600
                @" <xsl:template match='/'> " +
1601
                @" <out addition='{ext:add(2,2)}' " +
1602
                @" average='{ext:average((1,2,3,4,5,6))}' " +
1603
                @" firstchild='{ext:nameOfFirstChild(.)}' " +
1604
                @" timezone='{tz:StandardName($timezone)}' " +
1605
                @" sqrt2='{math:sqrt(2.0e0)}' " +
1606
                @" defaultNamespace='{env:defaultNamespace()}' " +
1607
                @" sqrtEmpty='{math:sqrt(())}'> " +
1608
                @" <xsl:copy-of select='ext:FirstChild((//ITEM)[1])'/> " +
1609
                @" <defaultNS value='{env:defaultNamespace()}' xsl:xpath-default-namespace='http://default.namespace.com/' /> " +
1610
                @" <combine1><xsl:sequence select='ext:combine(ext:FirstChild((//ITEM)[1]), count(*))'/></combine1> " +
1611
                @" <combine2><xsl:sequence select='ext:combine((//TITLE)[1], (//AUTHOR)[1])'/></combine2> " +
1612
                @" </out> " +
1613
                @" </xsl:template></xsl:transform>";
1614

    
1615
            // Register the integrated extension functions math:sqrt and env:defaultNamespace
1616
            processor.RegisterExtensionFunction(new Sqrt());
1617
            processor.RegisterExtensionFunction(new DefaultNamespace());
1618

    
1619
            // Create a transformer for the stylesheet.
1620
            XsltTransformer transformer = processor.NewXsltCompiler().Compile(new StringReader(s)).Load();
1621

    
1622
            // Load the source document (must be a wrapper around an XmlDocument for this test)
1623
            XmlDocument doc = new XmlDocument();
1624
            doc.Load(new XmlTextReader(samplesDir.AbsolutePath + "data/books.xml"));
1625
            XdmNode input = processor.NewDocumentBuilder().Wrap(doc);
1626

    
1627
            // Set the root node of the source document to be the initial context node
1628
            transformer.InitialContextNode = input;
1629

    
1630
            // Supply a parameter
1631
            transformer.SetParameter(new QName("", "timezone"),
1632
                      XdmAtomicValue.WrapExternalObject(TimeZone.CurrentTimeZone));
1633

    
1634
			// Create a serializer, with output to the standard output stream
1635
            Serializer serializer = new Serializer();
1636
            serializer.SetOutputWriter(Console.Out);
1637
            serializer.SetOutputProperty(Serializer.INDENT, "yes");
1638

    
1639
			// Transform the source XML and serialize the result document
1640
            transformer.Run(serializer);
1641
        }
1642

    
1643
    }
1644

    
1645
    /// <summary>
1646
    /// Show a transformation using calls to extension functions
1647
    /// </summary>
1648

    
1649
    public class XsltIntegratedExtension : Example
1650
    {
1651

    
1652
        public override string testName
1653
        {
1654
            get { return "XsltIntegratedExtension"; }
1655
        }
1656

    
1657
        public override void run(Uri samplesDir)
1658
        {
1659

    
1660
            // Create a Processor instance.
1661
            Processor processor = new Processor();
1662

    
1663
            // Identify the Processor version
1664
            Console.WriteLine(processor.ProductVersion);
1665

    
1666
            // Set diagnostics
1667
            //processor.SetProperty("http://saxon.sf.net/feature/trace-external-functions", "true");
1668

    
1669
            // Create the stylesheet
1670
            String s = @"<xsl:transform version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'" +
1671
                @" xmlns:math='http://example.math.co.uk/demo'> " +
1672
                @" <xsl:template name='go'> " +
1673
                @" <out sqrt2='{math:sqrt(2.0e0)}' " +
1674
                @" sqrtEmpty='{math:sqrt(())}'/> " +
1675
                @" </xsl:template></xsl:transform>";
1676

    
1677
            // Register the integrated extension function math:sqrt
1678
            processor.RegisterExtensionFunction(new Sqrt());
1679

    
1680
            // Create a transformer for the stylesheet.
1681
            XsltTransformer transformer = processor.NewXsltCompiler().Compile(new StringReader(s)).Load();
1682

    
1683
			// Set the name of the initial template
1684
            transformer.InitialTemplate = new QName("go");
1685

    
1686
			// Create a serializer, with output to the standard output stream
1687
            Serializer serializer = new Serializer();
1688
            serializer.SetOutputWriter(Console.Out);
1689
            serializer.SetOutputProperty(Serializer.INDENT, "yes");
1690

    
1691
			// Transform the source XML and serialize the result document
1692
            transformer.Run(serializer);
1693
        }
1694

    
1695
    }
1696

    
1697
    /// <summary>
1698
    /// Example extension function to compute a square root.
1699
    /// </summary>
1700

    
1701
    public class Sqrt : ExtensionFunctionDefinition
1702
    {
1703
        public override QName FunctionName
1704
        {
1705
            get
1706
            {
1707
                return new QName("http://example.math.co.uk/demo", "sqrt");
1708
            }
1709
        }
1710

    
1711
        public override int MinimumNumberOfArguments
1712
        {
1713
            get
1714
            {
1715
                return 1;
1716
            }
1717
        }
1718

    
1719
        public override int MaximumNumberOfArguments
1720
        {
1721
            get
1722
            {
1723
                return 1;
1724
            }
1725
        }
1726

    
1727
        public override XdmSequenceType[] ArgumentTypes
1728
        {
1729
            get
1730
            {
1731
                return new XdmSequenceType[]{
1732
                    new XdmSequenceType(XdmAtomicType.BuiltInAtomicType(QName.XS_DOUBLE), '?')
1733
                };
1734
            }
1735
        }
1736

    
1737
        public override XdmSequenceType ResultType(XdmSequenceType[] ArgumentTypes)
1738
        {
1739
            return new XdmSequenceType(XdmAtomicType.BuiltInAtomicType(QName.XS_DOUBLE), '?');
1740
        }
1741

    
1742
        public override bool TrustResultType
1743
        {
1744
            get
1745
            {
1746
                return true;
1747
            }
1748
        }
1749

    
1750

    
1751
        public override ExtensionFunctionCall MakeFunctionCall()
1752
        {
1753
            return new SqrtCall();
1754
        }
1755
    }
1756

    
1757
    internal class SqrtCall : ExtensionFunctionCall
1758
    {
1759
        public override IXdmEnumerator Call(IXdmEnumerator[] arguments, DynamicContext context)
1760
        {
1761
            Boolean exists = arguments[0].MoveNext();
1762
            if (exists)
1763
            {
1764
                XdmAtomicValue arg = (XdmAtomicValue)arguments[0].Current;
1765
                double val = (double)arg.Value;
1766
                double sqrt = System.Math.Sqrt(val);
1767
                XdmAtomicValue result = new XdmAtomicValue(sqrt);
1768
                return (IXdmEnumerator)result.GetEnumerator();
1769
            }
1770
            else
1771
            {
1772
                return EmptyEnumerator.INSTANCE;
1773
            }
1774
        }
1775

    
1776
	}
1777

    
1778
    /// <summary>
1779
    /// Example extension function to return the default namespace from the static context
1780
    /// </summary>
1781

    
1782
    public class DefaultNamespace : ExtensionFunctionDefinition
1783
    {
1784
        public override QName FunctionName
1785
        {
1786
            get
1787
            {
1788
                return new QName("http://example.env.co.uk/demo", "defaultNamespace");
1789
            }
1790
        }
1791

    
1792
        public override int MinimumNumberOfArguments
1793
        {
1794
            get
1795
            {
1796
                return 0;
1797
            }
1798
        }
1799

    
1800
        public override int MaximumNumberOfArguments
1801
        {
1802
            get
1803
            {
1804
                return 0;
1805
            }
1806
        }
1807

    
1808
        public override XdmSequenceType[] ArgumentTypes
1809
        {
1810
            get
1811
            {
1812
                return new XdmSequenceType[] { };
1813
            }
1814
        }
1815

    
1816
        public override bool DependsOnFocus
1817
        {
1818
            get
1819
            {
1820
                return true;
1821
                // actually it depends on the static context rather than the focus; but returning true is necessary
1822
                // to avoid the call being extracted to a global variable.
1823
            }
1824
        }
1825

    
1826
        public override XdmSequenceType ResultType(XdmSequenceType[] ArgumentTypes)
1827
        {
1828
            return new XdmSequenceType(XdmAtomicType.BuiltInAtomicType(QName.XS_STRING), '?');
1829
        }
1830

    
1831
        public override bool TrustResultType
1832
        {
1833
            get
1834
            {
1835
                return true;
1836
            }
1837
        }
1838

    
1839

    
1840
        public override ExtensionFunctionCall MakeFunctionCall()
1841
        {
1842
            return new DefaultNamespaceCall();
1843
        }
1844
    }
1845

    
1846
    internal class DefaultNamespaceCall : ExtensionFunctionCall
1847
    {
1848
        private string defaultNamespace;
1849

    
1850
        public override void SupplyStaticContext(StaticContext context)
1851
        {
1852
            defaultNamespace = context.GetNamespaceForPrefix("");
1853
        }
1854

    
1855
        public override IXdmEnumerator Call(IXdmEnumerator[] arguments, DynamicContext context)
1856
        {
1857
            if (defaultNamespace != null)
1858
            {
1859
                return (IXdmEnumerator)new XdmAtomicValue(defaultNamespace).GetEnumerator();
1860
            }
1861
            else
1862
            {
1863
                return EmptyEnumerator.INSTANCE;
1864
            }
1865
        }
1866

    
1867
	}
1868

    
1869
    /// <summary>
1870
    /// Show a query producing a document as its result and serializing this to a FileStream
1871
    /// </summary>
1872

    
1873
    public class XQueryToStream : Example
1874
    {
1875

    
1876
        public override string testName
1877
        {
1878
            get { return "XQueryToStream"; }
1879
        }
1880

    
1881
        public override void run(Uri samplesDir)
1882
        {
1883
            Processor processor = new Processor(true);
1884
            XQueryCompiler compiler = processor.NewXQueryCompiler();
1885
            compiler.BaseUri = samplesDir.ToString();
1886
            compiler.DeclareNamespace("saxon", "http://saxon.sf.net/");
1887
            XQueryExecutable exp = compiler.Compile("<saxon:example>{static-base-uri()}</saxon:example>");
1888
            XQueryEvaluator eval = exp.Load();
1889
            Serializer qout = new Serializer();
1890
            qout.SetOutputProperty(Serializer.METHOD, "xml");
1891
            qout.SetOutputProperty(Serializer.INDENT, "yes");
1892
            qout.SetOutputProperty(Serializer.SAXON_INDENT_SPACES, "1");
1893
            qout.SetOutputStream(new FileStream("testoutput.xml", FileMode.Create, FileAccess.Write));
1894
            Console.WriteLine("Output written to testoutput.xml");
1895
            eval.Run(qout);
1896
        }
1897

    
1898
    }
1899

    
1900
    /// <summary>
1901
    /// Show a query producing a single atomic value as its result and returning the value
1902
    /// to the C# application
1903
    /// </summary>
1904

    
1905
    public class XQueryToAtomicValue : Example
1906
    {
1907

    
1908
        public override string testName
1909
        {
1910
            get { return "XQueryToAtomicValue"; }
1911
        }
1912

    
1913
        public override void run(Uri samplesDir)
1914
        {
1915
            Processor processor = new Processor();
1916
            XQueryCompiler compiler = processor.NewXQueryCompiler();
1917
            XQueryExecutable exp = compiler.Compile("avg(for $i in 1 to 10 return $i * $i)");
1918
            XQueryEvaluator eval = exp.Load();
1919
            XdmAtomicValue result = (XdmAtomicValue)eval.EvaluateSingle();
1920
            Console.WriteLine("Result type: " + result.Value.GetType());
1921
            Console.WriteLine("Result value: " + (decimal)result.Value);
1922
        }
1923

    
1924
	}
1925

    
1926
	/// <summary>
1927
	/// Show a query producing a sequence as its result and returning the sequence
1928
	/// to the C# application in the form of an iterator. For each item in the
1929
	/// result, its string value is output.
1930
	/// </summary>
1931

    
1932
	public class XQueryToSequence : Example
1933
	{
1934

    
1935
		public override string testName
1936
		{
1937
			get { return "XQueryToSequence"; }
1938
		}
1939

    
1940
		public override void run(Uri samplesDir)
1941
		{
1942
			Processor processor = new Processor();
1943
			XQueryCompiler compiler = processor.NewXQueryCompiler();
1944
			XQueryExecutable exp = compiler.Compile("for $i in 1 to 10 return $i * $i");
1945
			XQueryEvaluator eval = exp.Load();
1946
			XdmValue value = eval.Evaluate();
1947
			IEnumerator e = value.GetEnumerator();
1948
			while (e.MoveNext())
1949
			{
1950
				XdmItem item = (XdmItem)e.Current;
1951
				Console.WriteLine(item.ToString());
1952
			}
1953

    
1954
		}
1955

    
1956
	}
1957

    
1958
    /// <summary>
1959
    /// Show a query producing a DOM as its input and producing a DOM as its output
1960
    /// </summary>
1961

    
1962
    public class XQueryToDom : Example
1963
    {
1964

    
1965
        public override string testName
1966
        {
1967
            get { return "XQueryToDom"; }
1968
        }
1969

    
1970
        public override void run(Uri samplesDir)
1971
        {
1972
            Processor processor = new Processor();
1973

    
1974
            XmlDocument input = new XmlDocument();
1975
            input.Load(new Uri(samplesDir, "data/books.xml").ToString());
1976
            XdmNode indoc = processor.NewDocumentBuilder().Build(new XmlNodeReader(input));
1977

    
1978
            XQueryCompiler compiler = processor.NewXQueryCompiler();
1979
            XQueryExecutable exp = compiler.Compile("<doc>{reverse(/*/*)}</doc>");
1980
            XQueryEvaluator eval = exp.Load();
1981
            eval.ContextItem = indoc;
1982
            DomDestination qout = new DomDestination();
1983
            eval.Run(qout);
1984
            XmlDocument outdoc = qout.XmlDocument;
1985
            Console.WriteLine(outdoc.OuterXml);
1986
        }
1987

    
1988
    }
1989

    
1990
    /// <summary>
1991
    /// Show a query producing a Saxon tree as its input and producing a Saxon tree as its output
1992
    /// </summary>
1993

    
1994
    public class XQueryToXdm : Example
1995
    {
1996

    
1997
        public override string testName
1998
        {
1999
            get { return "XQueryToXdm"; }
2000
        }
2001

    
2002
        public override void run(Uri samplesDir)
2003
        {
2004
            Processor processor = new Processor();
2005

    
2006
            DocumentBuilder loader = processor.NewDocumentBuilder();
2007
            loader.BaseUri = new Uri(samplesDir, "data/books.xml");
2008
            XdmNode indoc = loader.Build(loader.BaseUri);
2009

    
2010
            XQueryCompiler compiler = processor.NewXQueryCompiler();
2011
            XQueryExecutable exp = compiler.Compile("<doc>{reverse(/*/*)}</doc>");
2012
            XQueryEvaluator eval = exp.Load();
2013
            eval.ContextItem = indoc;
2014
            XdmDestination qout = new XdmDestination();
2015
            eval.Run(qout);
2016
            XdmNode outdoc = qout.XdmNode;
2017
            Console.WriteLine(outdoc.OuterXml);
2018
        }
2019

    
2020
    }
2021

    
2022
    /// <summary>
2023
    /// Show a query making a direct call to a user-defined function defined in the query
2024
    /// </summary>
2025

    
2026
    public class XQueryCallFunction : Example
2027
    {
2028

    
2029
        public override string testName
2030
        {
2031
            get { return "XQueryCallFunction"; }
2032
        }
2033

    
2034
        public override void run(Uri samplesDir)
2035
        {
2036
            Processor processor = new Processor();
2037

    
2038
            XQueryCompiler qc = processor.NewXQueryCompiler();
2039
            Uri uri = new Uri(samplesDir, "data/books.xml");
2040
            XQueryExecutable exp1 = qc.Compile("declare namespace f='f.ns';" +
2041
                   "declare variable $z := 1 + xs:integer(doc-available('" + uri.ToString() + "'));" +
2042
                   "declare variable $p as xs:integer external;" +
2043
                   "declare function f:t1($v1 as xs:integer) { " +
2044
                   "   $v1 div $z + $p" +
2045
                   "};" +
2046
                   "10");
2047
            XQueryEvaluator ev = exp1.Load();
2048
            ev.SetExternalVariable(new QName("", "p"), new XdmAtomicValue(39));
2049
            XdmValue v1 = new XdmAtomicValue(10);
2050
            XdmValue result = ev.CallFunction(new QName("f.ns", "f:t1"), new XdmValue[] { v1 });
2051
            Console.WriteLine("First result (expected 44): " + result.ToString());
2052
            v1 = new XdmAtomicValue(20);
2053
            result = ev.CallFunction(new QName("f.ns", "f:t1"), new XdmValue[] { v1 });
2054
            Console.WriteLine("Second result (expected 49): " + result.ToString());
2055
        }
2056

    
2057
    }
2058

    
2059
    /// <summary>
2060
    /// Show a query reading an input document using an XmlReader (the .NET XML parser)
2061
    /// </summary>
2062

    
2063
    public class XQueryFromXmlReader : Example
2064
    {
2065

    
2066
        public override string testName
2067
        {
2068
            get { return "XQueryFromXmlReader"; }
2069
        }
2070

    
2071
        public override void run(Uri samplesDir)
2072
        {
2073
            Processor processor = new Processor();
2074

    
2075
            String inputFileName = new Uri(samplesDir, "data/books.xml").ToString();
2076
            XmlTextReader reader = new XmlTextReader(inputFileName,
2077
                UriConnection.getReadableUriStream(new Uri(samplesDir, "data/books.xml")));
2078
            //new FileStream(inputFileName, FileMode.Open, FileAccess.Read));
2079
            reader.Normalization = true;
2080

    
2081
            // add a validating reader - not to perform validation, but to expand entity references
2082
            XmlValidatingReader validator = new XmlValidatingReader(reader);
2083
            validator.ValidationType = ValidationType.None;
2084

    
2085
            XdmNode doc = processor.NewDocumentBuilder().Build(validator);
2086

    
2087
            XQueryCompiler compiler = processor.NewXQueryCompiler();
2088
            XQueryExecutable exp = compiler.Compile("/");
2089
            XQueryEvaluator eval = exp.Load();
2090
            eval.ContextItem = doc;
2091
            Serializer qout = new Serializer();
2092
            qout.SetOutputProperty(Serializer.METHOD, "xml");
2093
            qout.SetOutputProperty(Serializer.INDENT, "yes");
2094
			qout.SetOutputStream(new FileStream("testoutput2.xml", FileMode.Create, FileAccess.Write));
2095
			Console.WriteLine("Output written to testoutput2.xml");
2096
            eval.Run(qout);
2097
        }
2098

    
2099
    }
2100

    
2101
    /// <summary>
2102
    /// Show a query producing a sequence as its result and returning the sequence
2103
    /// to the C# application in the form of an iterator. The sequence is then
2104
    /// output by serializing each item individually, with each item on a new line.
2105
    /// </summary>
2106

    
2107
    public class XQueryToSerializedSequence : Example
2108
    {
2109

    
2110
        public override string testName
2111
        {
2112
            get { return "XQueryToSerializedSequence"; }
2113
        }
2114

    
2115
        public override void run(Uri samplesDir)
2116
        {
2117
            Processor processor = new Processor();
2118
            String inputFileName = new Uri(samplesDir, "data/books.xml").ToString();
2119
            //XmlTextReader reader = new XmlTextReader(inputFileName,
2120
            //    new FileStream(inputFileName, FileMode.Open, FileAccess.Read));
2121
            XmlTextReader reader = new XmlTextReader(inputFileName,
2122
                UriConnection.getReadableUriStream(new Uri(samplesDir, "data/books.xml")));
2123
            reader.Normalization = true;
2124

    
2125
            // add a validating reader - not to perform validation, but to expand entity references
2126
            XmlValidatingReader validator = new XmlValidatingReader(reader);
2127
            validator.ValidationType = ValidationType.None;
2128

    
2129
            XdmNode doc = processor.NewDocumentBuilder().Build(reader);
2130
            XQueryCompiler compiler = processor.NewXQueryCompiler();
2131
            XQueryExecutable exp = compiler.Compile("//ISBN");
2132

    
2133
            XQueryEvaluator eval = exp.Load();
2134
            eval.ContextItem = doc;
2135

    
2136
            foreach (XdmNode node in eval)
2137
            {
2138
                Console.WriteLine(node.OuterXml);
2139
            }
2140
        }
2141

    
2142
    }
2143

    
2144
    /// <summary>
2145
    /// Show a query that takes a parameter (external variable) as input.
2146
    /// The query produces a single atomic value as its result and returns the value
2147
    /// to the C# application. 
2148
    /// </summary>
2149

    
2150
    public class XQueryUsingParameter : Example
2151
    {
2152

    
2153
        public override string testName
2154
        {
2155
            get { return "XQueryUsingParameter"; }
2156
        }
2157

    
2158
        public override void run(Uri samplesDir)
2159
        {
2160
            Processor processor = new Processor();
2161
            XQueryCompiler compiler = processor.NewXQueryCompiler();
2162
            compiler.DeclareNamespace("p", "http://saxon.sf.net/ns/p");
2163
            XQueryExecutable exp = compiler.Compile(
2164
                    "declare variable $p:in as xs:integer external; $p:in * $p:in");
2165
            XQueryEvaluator eval = exp.Load();
2166
            eval.SetExternalVariable(new QName("http://saxon.sf.net/ns/p", "p:in"), new XdmAtomicValue(12));
2167
            XdmAtomicValue result = (XdmAtomicValue)eval.EvaluateSingle();
2168
            Console.WriteLine("Result type: " + result.Value.GetType());
2169
            Console.WriteLine("Result value: " + (long)result.Value);
2170
        }
2171

    
2172
    }
2173

    
2174
    /// <summary>
2175
    /// Show a query consisting of two modules, using a QueryResolver to resolve
2176
    /// the "import module" declaration
2177
    /// </summary>
2178

    
2179
    public class XQueryMultiModule : Example
2180
    {
2181

    
2182
        public override string testName
2183
        {
2184
            get { return "XQueryMultiModule"; }
2185
        }
2186

    
2187
        public override void run(Uri samplesDir)
2188
        {
2189

    
2190
            String mod1 = "import module namespace m2 = 'http://www.example.com/module2';" +
2191
                          "m2:square(3)";
2192

    
2193
            String mod2 = "module namespace m2 = 'http://www.example.com/module2';" +
2194
                          "declare function m2:square($p) { $p * $p };";
2195

    
2196
            Processor processor = new Processor();
2197
            XQueryCompiler compiler = processor.NewXQueryCompiler();
2198

    
2199
            InlineModuleResolver resolver = new InlineModuleResolver();
2200
            resolver.AddModule(new Uri("http://www.example.com/module2"), mod2);
2201
            compiler.QueryResolver = resolver;
2202
            XQueryExecutable exp = compiler.Compile(mod1);
2203
            XQueryEvaluator eval = exp.Load();
2204

    
2205
            XdmAtomicValue result = (XdmAtomicValue)eval.EvaluateSingle();
2206
            Console.WriteLine("Result type: " + result.Value.GetType());
2207
            Console.WriteLine("Result value: " + (long)result.Value);
2208
        }
2209

    
2210
        // A simple QueryResolver designed to show that the actual query
2211
        // text can come from anywhere: in this case, the resolver maintains
2212
        // a simple mapping of module URIs onto strings.
2213

    
2214
        public class InlineModuleResolver : IQueryResolver
2215
        {
2216

    
2217
            private Hashtable modules = new Hashtable();
2218

    
2219
            public void AddModule(Uri moduleName, String moduleText)
2220
            {
2221
                modules.Add(moduleName, moduleText);
2222
            }
2223

    
2224
            public Uri[] GetModules(String moduleUri, Uri baseUri, String[] locationHints)
2225
            {
2226
                Uri[] result = { new Uri(moduleUri) };
2227
                return result;
2228
            }
2229

    
2230
            public Object GetEntity(Uri absoluteUri)
2231
            {
2232
                return modules[absoluteUri];
2233
            }
2234
        }
2235

    
2236
	}
2237

    
2238
	/// <summary>
2239
	/// Demonstrate using a try-catch expression in the query, a feature of XQuery 3.0
2240
	/// </summary>
2241

    
2242
	public class XQueryTryCatch : Example
2243
	{
2244

    
2245
		public override string testName
2246
		{
2247
			get { return "XQueryTryCatch"; }
2248
		}
2249

    
2250
		public override void run(Uri samplesDir)
2251
		{
2252

    
2253
			String query = "xquery version '3.0'; try {doc('book.xml')}catch * {\"XQuery 3.0 catch clause - file not found.\"}";
2254
			Processor processor = new Processor();
2255

    
2256
			XQueryCompiler compiler = processor.NewXQueryCompiler();
2257
			compiler.XQueryLanguageVersion = "3.0";
2258
			XQueryExecutable exp = compiler.Compile(query);
2259
			XQueryEvaluator eval = exp.Load();
2260
			Serializer qout = new Serializer();
2261
			eval.Run(qout);
2262
		}
2263

    
2264
	}
2265

    
2266
    /// <summary>
2267
    /// Demonstrate XQuery extensibility using user-written extension functions
2268
	/// </summary>
2269
	/// <remarks>Note: If SamplesExtensions is compiled to a different assembly than ExamplesEE, use 
2270
	/// the namespace URI clitype:SampleExtensions.SampleExtensions?asm=ASSEMBLY_NAME_HERE
2271
	/// </remarks>
2272

    
2273
    public class XQueryExtensibility : Example
2274
    {
2275

    
2276
        public override string testName
2277
        {
2278
            get { return "XQueryExtensibility"; }
2279
        }
2280

    
2281
        public override void run(Uri samplesDir)
2282
        {
2283
            String query =
2284
                "declare namespace ext = \"clitype:SampleExtensions.SampleExtensions?asm=ExamplesEE\";" +
2285
                "<out>" +
2286
                "  <addition>{ext:add(2,2)}</addition>" +
2287
                "  <average>{ext:average((1,2,3,4,5,6))}</average>" +
2288
                "  <language>{ext:hostLanguage()}</language>" +
2289
                "</out>";
2290

    
2291
            Processor processor = new Processor(true);
2292
            XQueryCompiler compiler = processor.NewXQueryCompiler();
2293
            XQueryExecutable exp = compiler.Compile(query);
2294
            XQueryEvaluator eval = exp.Load();
2295
            Serializer qout = new Serializer();
2296
            eval.Run(qout);
2297
        }
2298

    
2299
    }
2300

    
2301
    /// <summary>
2302
    /// Demonstrate XQuery Update
2303
    /// </summary>
2304

    
2305
    public class XQueryUpdate : Example
2306
    {
2307

    
2308
        public override string testName
2309
        {
2310
            get { return "XQueryUpdate"; }
2311
        }
2312

    
2313
        public override void run(Uri samplesDir)
2314
        {
2315
            Processor processor = new Processor(true);
2316

    
2317
            DocumentBuilder loader = processor.NewDocumentBuilder();
2318
            loader.BaseUri = new Uri(samplesDir, "data/books.xml");
2319
            loader.TreeModel = TreeModel.LinkedTree;
2320
            XdmNode indoc = loader.Build(new Uri(samplesDir, "data/books.xml"));
2321

    
2322
            Console.Out.WriteLine("=========== BEFORE UPDATE ===========");
2323

    
2324
            Serializer serializer0 = new Serializer();
2325
            serializer0.SetOutputProperty(Serializer.METHOD, "xml");
2326
            serializer0.SetOutputProperty(Serializer.INDENT, "yes");
2327
            serializer0.SetOutputWriter(Console.Out);
2328
            processor.WriteXdmValue(indoc, serializer0);
2329

    
2330
            String query =
2331
                "for $i in //PRICE return \n" +
2332
                "replace value of node $i with $i - 0.05";
2333

    
2334
            XQueryCompiler compiler = processor.NewXQueryCompiler();
2335
            compiler.UpdatingEnabled = true;
2336
            XQueryExecutable exp = compiler.Compile(query);
2337
            XQueryEvaluator eval = exp.Load();
2338
            eval.ContextItem = indoc;
2339
            XdmNode[] updatedNodes = eval.RunUpdate();
2340

    
2341
			// Serialize the updated result to Console.out
2342
            foreach (XdmNode root in updatedNodes)
2343
            {
2344
                Uri documentUri = root.DocumentUri;
2345
                if (documentUri != null && documentUri.Scheme == "file")
2346
                {
2347
                    Serializer serializer = new Serializer();
2348
                    serializer.SetOutputProperty(Serializer.METHOD, "xml");
2349
                    serializer.SetOutputProperty(Serializer.INDENT, "yes");
2350
					Console.Out.WriteLine("=========== AFTER UPDATE ===========");
2351
					serializer.SetOutputWriter(Console.Out);
2352
                    processor.WriteXdmValue(root, serializer);
2353
                }
2354
            }
2355

    
2356
			// To serialize to the original source file, replace the above code with the following
2357

    
2358
			//foreach (XdmNode root in updatedNodes)
2359
			//{
2360
			//	Uri documentUri = root.DocumentUri;
2361
			//	if (documentUri != null && documentUri.Scheme == "file")
2362
			//	{
2363
			//		Stream stream = UriConnection.getWritableUriStream(documentUri);
2364
			//		Serializer serializer = new Serializer();
2365
			//		serializer.SetOutputProperty(Serializer.METHOD, "xml");
2366
			//		serializer.SetOutputProperty(Serializer.INDENT, "yes");
2367
			//		serializer.SetOutputStream(stream);
2368
			//		processor.WriteXdmValue(root, serializer);
2369
			//	}
2370
			//}
2371
			//
2372
			//Console.Out.WriteLine("=========== AFTER UPDATE ===========");
2373
			//
2374
			//processor.WriteXdmValue(indoc, serializer0);
2375
        }
2376
	}
2377

    
2378
    /// <summary>
2379
	/// Demonstrate schema aware XQuery
2380
    /// </summary>
2381

    
2382
    public class XQuerySchemaAware : Example
2383
    {
2384

    
2385
        public override string testName
2386
        {
2387
            get { return "XQuerySchemaAware"; }
2388
        }
2389

    
2390
        public override void run(Uri samplesDir)
2391
        {
2392
			Processor processor = new Processor(true);
2393

    
2394
			String inputFileName = new Uri (samplesDir, "data/books.xml").ToString();
2395
			String inputSchemaName = new Uri (samplesDir, "data/books.xsd").ToString();
2396
			String query = "import schema default element namespace \"\" at \"" + inputSchemaName + "\";\n" +
2397
				"for $integer in (validate { doc(\"" + inputFileName + "\") })//schema-element(ITEM)\n" +
2398
                                "return <OUTPUT>{$integer}</OUTPUT>";
2399

    
2400
            XQueryCompiler compiler = processor.NewXQueryCompiler();
2401
            compiler.XQueryLanguageVersion = "1.0";
2402
            XQueryExecutable exp = compiler.Compile(query);
2403
            XQueryEvaluator eval = exp.Load();
2404
			Serializer qout = new Serializer();
2405
			qout.SetOutputProperty(Serializer.METHOD, "xml");
2406
			qout.SetOutputProperty(Serializer.INDENT, "yes");
2407
            eval.Run(qout);
2408
        }
2409

    
2410
    }
2411

    
2412
    /// <summary>
2413
	/// Demonstrate schema aware XPath
2414
    /// </summary>
2415

    
2416
    public class XPathSchemaAware : Example
2417
    {
2418

    
2419
        public override string testName
2420
        {
2421
            get { return "XPathSchemaAware"; }
2422
        }
2423

    
2424
        public override void run(Uri samplesDir)
2425
        {
2426
            Processor processor = new Processor(true);
2427

    
2428

    
2429
            String inputFileName = new Uri(samplesDir, "data/books.xml").ToString();
2430

    
2431
            processor.SchemaManager.Compile(new Uri(samplesDir, "data/books.xsd"));
2432

    
2433
            // add a reader
2434
			XmlReaderSettings settings = new XmlReaderSettings();
2435
			settings.DtdProcessing = DtdProcessing.Ignore;
2436
			XmlReader xmlReader = XmlReader.Create(UriConnection.getReadableUriStream(new Uri(samplesDir, "data/books.xml")), settings);
2437

    
2438
            DocumentBuilder builder = processor.NewDocumentBuilder();
2439

    
2440
            builder.SchemaValidationMode = SchemaValidationMode.Strict;
2441
            XdmNode doc = builder.Build(xmlReader);
2442

    
2443
            XPathCompiler compiler = processor.NewXPathCompiler();
2444
            compiler.ImportSchemaNamespace("");
2445
            XPathExecutable exp = compiler.Compile("if (//ITEM[@CAT='MMP']/QUANTITY instance of element(*,xs:integer)*) then 'true' else 'false'");
2446
            XPathSelector eval = exp.Load();
2447
            eval.ContextItem = doc;
2448
            XdmAtomicValue result = (XdmAtomicValue)eval.EvaluateSingle();
2449
            Console.WriteLine("Result type: " + result.ToString());
2450
        }
2451

    
2452
    }
2453

    
2454
    /// <summary>
2455
    /// Show XSLT streaming of document
2456
    /// </summary>
2457

    
2458
    public class XsltStreamDoc : Example
2459
    {
2460

    
2461
        public override string testName
2462
        {
2463
            get { return "XsltStreamDoc"; }
2464
        }
2465

    
2466
        public override void run(Uri samplesDir)
2467
        {
2468
            Processor processor = new Processor(true);
2469

    
2470
            // Create the stylesheet
2471
            String s = "<xsl:transform version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform' xmlns:saxon='http://saxon.sf.net/'>\n" +
2472
                " <xsl:template name='main'> " +
2473
                " <xsl:value-of select=\"count(saxon:stream(doc('" + new Uri(samplesDir, "data/othello.xml").ToString() + "')//LINE[count(tokenize(.,'/s')) &gt; 0] ))\" />" +
2474
                " </xsl:template></xsl:transform>";
2475

    
2476
            // Create a transformer for the stylesheet.
2477
            XsltTransformer transformer = processor.NewXsltCompiler().Compile(new StringReader(s)).Load();
2478

    
2479
			// Set the name of the initial template
2480
            transformer.InitialTemplate = new QName("main");
2481

    
2482
            // Create a serializer
2483
            Serializer serializer = new Serializer();
2484
            serializer.SetOutputWriter(Console.Out);
2485
            //  serializer.SetOutputProperty(Serializer.INDENT, "yes");
2486

    
2487
            // Transform the source XML to System.out.
2488
            transformer.Run(serializer);
2489

    
2490

    
2491
        }
2492

    
2493
    }
2494

    
2495
    /// <summary>
2496
    /// Show validation of an instance document against a schema, 
2497
	/// if the document is valid then run a schema aware query
2498
    /// </summary>
2499

    
2500
    public class Validate : Example
2501
    {
2502

    
2503
        public override string testName
2504
        {
2505
            get { return "Validate"; }
2506
        }
2507

    
2508
        public override void run(Uri samplesDir)
2509
        {
2510
            // Load a schema
2511

    
2512
			Processor processor = new Processor(true);
2513
            processor.SetProperty("http://saxon.sf.net/feature/timing", "true");
2514
            processor.SetProperty("http://saxon.sf.net/feature/validation-warnings", "false"); //Set to true to suppress the exception
2515
            SchemaManager manager = processor.SchemaManager;
2516
            manager.XsdVersion = "1.1";
2517
            manager.ErrorList = new ArrayList();
2518
            Uri schemaUri = new Uri(samplesDir, "data/books.xsd");
2519

    
2520
            try
2521
            {
2522
                manager.Compile(schemaUri);
2523
            }
2524
            catch (Exception e)
2525
            {
2526
                Console.WriteLine(e);
2527
                Console.WriteLine("Schema compilation failed with " + manager.ErrorList.Count + " errors");
2528
                foreach (StaticError error in manager.ErrorList)
2529
                {
2530
                    Console.WriteLine("At line " + error.LineNumber + ": " + error.Message);
2531
                }
2532
                return;
2533
            }
2534

    
2535

    
2536
            // Use this to validate an instance document
2537

    
2538
            SchemaValidator validator = manager.NewSchemaValidator();
2539
            //Uri instanceUri = new Uri(samplesDir, "data/books-invalid.xml");
2540
            //validator.SetSource(instanceUri);
2541

    
2542
			XmlReaderSettings settings = new XmlReaderSettings();
2543
			settings.DtdProcessing = DtdProcessing.Ignore;
2544
			String inputFileName = new Uri(samplesDir, "data/books-invalid.xml").ToString();
2545
			XmlReader xmlReader = XmlReader.Create(inputFileName, settings);
2546
			validator.SetSource(xmlReader);
2547
			Console.WriteLine("Validating input file " + inputFileName);
2548
            validator.ErrorList = new ArrayList();
2549
            XdmDestination psvi = new XdmDestination();
2550
            validator.SetDestination(psvi);
2551

    
2552
            try
2553
            {
2554
                validator.Run();
2555
            }
2556
            catch (Exception e)
2557
            {
2558
                Console.WriteLine(e);
2559
                Console.WriteLine("Instance validation failed with " + validator.ErrorList.Count + " errors");
2560
                foreach (StaticError error in validator.ErrorList)
2561
                {
2562
                    Console.WriteLine("At line " + error.LineNumber + ": " + error.Message);
2563
                }
2564
                return;
2565
            }
2566

    
2567
			Console.WriteLine("Input file is valid");
2568

    
2569
            // Run a query on the result to check that it has type annotations
2570

    
2571
			XQueryCompiler xq = processor.NewXQueryCompiler();
2572
			xq.SchemaAware = true;
2573
            XQueryEvaluator xv = xq.Compile("data((//PRICE)[1]) instance of xs:decimal").Load();
2574
            xv.ContextItem = psvi.XdmNode;
2575
            Console.WriteLine("Price is decimal? " + xv.EvaluateSingle().ToString());
2576
        }
2577
    }
2578

    
2579

    
2580

    
2581
    public class UriConnection
2582
    {
2583

    
2584
        // Get a stream for reading from a file:// URI
2585

    
2586
        public static Stream getReadableUriStream(Uri uri)
2587
        {
2588
            WebRequest request = (WebRequest)WebRequest.Create(uri);
2589
            return request.GetResponse().GetResponseStream();
2590
        }
2591

    
2592
        // Get a stream for writing to a file:// URI
2593

    
2594
        public static Stream getWritableUriStream(Uri uri)
2595
        {
2596
            FileWebRequest request = (FileWebRequest)WebRequest.CreateDefault(uri);
2597
            request.Method = "POST";
2598
            return request.GetRequestStream();
2599
        }
2600
    }
2601

    
2602
    ///
2603
    /// A sample XmlResolver. In the case of a URI ending with ".txt", it returns the
2604
    /// URI itself, wrapped as an XML document. In the case of the URI "empty.xslt", it returns an empty
2605
    /// stylesheet. In all other cases, it returns null, which has the effect of delegating
2606
    /// processing to the standard XmlResolver.
2607
    ///
2608

    
2609
    public class UserXmlResolver : XmlUrlResolver
2610
    {
2611

    
2612
        public String Message = null;
2613

    
2614
        public override object GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn)
2615
        {
2616
            if (Message != null)
2617
            {
2618
                Console.WriteLine(Message + absoluteUri + " (role=" + role + ")");
2619
            }
2620

    
2621
            if (absoluteUri.ToString().EndsWith(".txt"))
2622
            {
2623
                MemoryStream ms = new MemoryStream();
2624
                StreamWriter tw = new StreamWriter(ms);
2625
                tw.Write("<uri>");
2626
                tw.Write(absoluteUri);
2627
                tw.Write("</uri>");
2628
                tw.Flush();
2629
                return new MemoryStream(ms.GetBuffer(), 0, (int)ms.Length);
2630
            }
2631
            if (absoluteUri.ToString().EndsWith("empty.xslt"))
2632
            {
2633
                String ss = "<transform xmlns='http://www.w3.org/1999/XSL/Transform' version='2.0'/>";
2634
                MemoryStream ms = new MemoryStream();
2635
                StreamWriter tw = new StreamWriter(ms);
2636
                tw.Write(ss);
2637
                tw.Flush();
2638
                return new MemoryStream(ms.GetBuffer(), 0, (int)ms.Length);
2639
            }
2640
            else
2641
            {
2642
                return null;
2643
            }
2644
        }
2645
    }
2646

    
2647
    public class UserResultDocumentHandler : IResultDocumentHandler
2648
    {
2649

    
2650
        private Hashtable results;
2651

    
2652
        public UserResultDocumentHandler(Hashtable table)
2653
        {
2654
            this.results = table;
2655
        }
2656

    
2657
        public XmlDestination HandleResultDocument(string href, Uri baseUri)
2658
        {
2659
            DomDestination destination = new DomDestination();
2660
            results[href] = destination;
2661
            return destination;
2662
        }
2663

    
2664
    }
2665
}
2666

    
2667

    
2668
//
2669
// The contents of this file are subject to the Mozilla Public License Version 1.0 (the "License");
2670
// you may not use this file except in compliance with the License. You may obtain a copy of the
2671
// License at http://www.mozilla.org/MPL/
2672
//
2673
// Software distributed under the License is distributed on an "AS IS" basis,
2674
// WITHOUT WARRANTY OF ANY KIND, either express or implied.
2675
// See the License for the specific language governing rights and limitations under the License.
2676
//
2677
// The Original Code is: all this file.
2678
//
2679
// The Initial Developer of the Original Code is Michael H. Kay.
2680
//
2681
// Portions created by (your name) are Copyright (C) (your legal entity). All Rights Reserved.
2682
//
2683
// Contributor(s): none.
2684
//
2685

    
2686

    
2687

    
(1-1/5)