Project

Profile

Help

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

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

    
24

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

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

    
69
            Boolean ask = true;
70
            String test = "all";
71

    
72
            String samplesPath = null;
73
            Uri samplesDir;
74

    
75
            foreach (String s in argv)
76
            {
77
                if (s.StartsWith("-test:"))
78
                {
79
                    test = s.Substring(6);
80
                }
81
                else if (s.StartsWith("-dir:"))
82
                {
83
                    samplesPath = s.Substring(5);
84
                }
85
                else if (s == "-ask:yes")
86
                {
87
                    // no action
88
                }
89
                else if (s == "-ask:no")
90
                {
91
                    ask = false;
92
                }
93
                else if (s == "-?")
94
                {
95
                    Console.WriteLine("ExamplesHE -dir:samples -test:testname -ask:yes|no");
96
                }
97
                else
98
                {
99
                    Console.WriteLine("Unrecognized Argument: " + s);
100
                    return;
101
                }
102
            }
103
            if (samplesPath != null)
104
            {
105
                if (samplesPath.StartsWith("file:///"))
106
                {
107
                    samplesPath = samplesPath.Substring(8);
108
                }
109
                else if (samplesPath.StartsWith("file:/"))
110
                {
111
                    samplesPath = samplesPath.Substring(6);
112
                }
113

    
114
            }
115
            else
116
            {
117
                String home = Environment.GetEnvironmentVariable("SAXON_HOME");
118
                if (home == null)
119
                {
120
                    Console.WriteLine("No input directory supplied, and SAXON_HOME is not set");
121
                    return;
122
                }
123
                else
124
                {
125
                    if (!(home.EndsWith("/") || home.EndsWith("\\")))
126
                    {
127
                        home = home + "/";
128
                    }
129
                    samplesPath = home + "samples/";
130
                }
131
            }
132

    
133
            if (!(samplesPath.EndsWith("/") || samplesPath.EndsWith("\\")))
134
            {
135
                samplesPath = samplesPath + "/";
136
            }
137

    
138
            if (!File.Exists(samplesPath + "data/books.xml"))
139
            {
140
                Console.WriteLine("Supplied samples directory " + samplesPath + " does not contain the Saxon sample data files");
141
                return;
142
            }
143

    
144
            try
145
            {
146
                samplesDir = new Uri(samplesPath);
147
            }
148
            catch
149
            {
150
                Console.WriteLine("Invalid URI for samples directory: " + samplesPath);
151
                return;
152
			}
153

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

    
200
    ///<summary>
201
    /// Each of the example programs is implemented as a subclass of the abstract class Example
202
    ///</summary> 
203

    
204

    
205
    public abstract class Example
206
    {
207
        /// <summary>
208
        /// Read-only property: the name of the test example
209
        /// </summary>
210
        public abstract String testName { get; }
211
        /// <summary>
212
        /// Entry point for running the example
213
        /// </summary>
214
        public abstract void run(Uri samplesDir);
215
    }
216

    
217
    /// <summary>
218
	/// Evaluate an XPath expression selecting from a source document supplied as a URI
219
    /// </summary>
220

    
221
    public class XPathSimple : Example
222
    {
223

    
224
        public override String testName
225
        {
226
            get { return "XPathSimple"; }
227
        }
228

    
229
        public override void run(Uri samplesDir)
230
        {
231
            // Create a Processor instance.
232
            Processor processor = new Processor();
233

    
234
            // Load the source document
235
            XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/books.xml"));
236

    
237
            // Create an XPath compiler
238
            XPathCompiler xpath = processor.NewXPathCompiler();
239

    
240
            // Enable caching, so each expression is only compiled once
241
            xpath.Caching = true;
242

    
243
            // Compile and evaluate some XPath expressions
244
            foreach (XdmItem item in xpath.Evaluate("//ITEM", input))
245
            {
246
                Console.WriteLine("TITLE: " + xpath.EvaluateSingle("string(TITLE)", item));
247
                Console.WriteLine("PRICE: " + xpath.EvaluateSingle("string(PRICE)", item));
248
            }
249
        }
250
	}
251

    
252
	/// <summary>
253
	/// Evaluate an XPath expression against a source document, returning its effective boolean value
254
	/// </summary>
255

    
256
    public class XPathSimple2 : Example
257
    {
258

    
259
        public override String testName
260
        {
261
            get { return "XPathSimple2"; }
262
        }
263

    
264
        public override void run(Uri samplesDir)
265
        {
266
            // Create a Processor instance.
267
            Processor processor = new Processor();
268

    
269
            // Load the source document
270
            XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/books.xml"));
271

    
272
            // Create an XPath compiler
273
            XPathCompiler xpath = processor.NewXPathCompiler();
274

    
275
            // Enable caching, so each expression is only compiled once
276
            xpath.Caching = true;
277
            
278
            // Compile and evaluate an XPath expression
279
			XPathSelector selector = xpath.Compile("//ITEM").Load();
280
            selector.ContextItem = input;
281
			Console.WriteLine(selector.EffectiveBooleanValue());
282

    
283
        }
284
    }
285

    
286
    /// <summary>
287
	/// Evaluate an XPath expression using variables (and no source document)
288
    /// </summary>
289

    
290
    public class XPathVariables : Example
291
    {
292

    
293
        public override String testName
294
        {
295
            get { return "XPathVariables"; }
296
        }
297

    
298
        public override void run(Uri samplesDir)
299
        {
300
            // Create a Processor instance.
301
            Processor processor = new Processor();
302

    
303
            // Create the XPath expression.
304
            XPathCompiler compiler = processor.NewXPathCompiler();
305
            compiler.DeclareVariable(new QName("", "a"));
306
            compiler.DeclareVariable(new QName("", "b"));
307
            XPathSelector selector = compiler.Compile("$a + $b").Load();
308

    
309
            // Set the values of the variables
310
            selector.SetVariable(new QName("", "a"), new XdmAtomicValue(2));
311
            selector.SetVariable(new QName("", "b"), new XdmAtomicValue(3));
312

    
313
            // Evaluate the XPath expression
314
            Console.WriteLine(selector.EvaluateSingle().ToString());
315
        }
316
    }
317

    
318
    /// <summary>
319
	/// Evaluate an XPath expression using variables without explicit declaration
320
    /// </summary>
321

    
322
    public class XPathUndeclaredVariables : Example
323
    {
324

    
325
        public override String testName
326
        {
327
            get { return "XPathUndeclaredVariables"; }
328
        }
329

    
330
        public override void run(Uri samplesDir)
331
        {
332
            // Create a Processor instance.
333
            Processor processor = new Processor();
334

    
335
            // Create the XPath expression.
336
            XPathCompiler compiler = processor.NewXPathCompiler();
337
            compiler.AllowUndeclaredVariables = true;
338
            XPathExecutable expression = compiler.Compile("$a + $b");
339
            XPathSelector selector = expression.Load();
340

    
341
            // Set the values of the variables
342
            IEnumerator vars = expression.EnumerateExternalVariables();
343
            while (vars.MoveNext())
344
            {
345
                selector.SetVariable((QName)vars.Current, new XdmAtomicValue(10));
346
            }
347

    
348
            // Evaluate the XPath expression
349
            Console.WriteLine(selector.EvaluateSingle().ToString());
350
        }
351
    }
352

    
353
    /// <summary>
354
	/// Evaluate an XPath expression throwing a static error
355
    /// </summary>
356

    
357
    public class XPathWithStaticError : Example
358
    {
359

    
360
        public override String testName
361
        {
362
            get { return "XPathWithStaticError"; }
363
        }
364

    
365
        public override void run(Uri samplesDir)
366
        {
367
            // Create a Processor instance.
368
            Processor processor = new Processor();
369

    
370
            // Create the XPath expression.
371
            XPathCompiler compiler = processor.NewXPathCompiler();
372
            compiler.AllowUndeclaredVariables = true;
373
            XPathExecutable expression = compiler.Compile("1 + unknown()");
374
            XPathSelector selector = expression.Load();
375

    
376
            // Evaluate the XPath expression
377
            Console.WriteLine(selector.EvaluateSingle().ToString());
378
        }
379
    }
380

    
381
    /// <summary>
382
	/// Evaluate an XPath expression throwing a dynamic error
383
    /// </summary>
384

    
385
    public class XPathWithDynamicError : Example
386
    {
387

    
388
        public override String testName
389
        {
390
            get { return "XPathWithDynamicError"; }
391
        }
392

    
393
        public override void run(Uri samplesDir)
394
        {
395
            // Create a Processor instance.
396
            Processor processor = new Processor();
397

    
398
            // Create the XPath expression.
399
            XPathCompiler compiler = processor.NewXPathCompiler();
400
            compiler.AllowUndeclaredVariables = true;
401
            XPathExecutable expression = compiler.Compile("$a gt $b");
402
            XPathSelector selector = expression.Load();
403

    
404
            // Set the values of the variables
405
            selector.SetVariable(new QName("", "a"), new XdmAtomicValue(10));
406
            selector.SetVariable(new QName("", "b"), new XdmAtomicValue("Paris"));
407

    
408
            // Evaluate the XPath expression
409
            Console.WriteLine(selector.EvaluateSingle().ToString());
410
        }
411
    }
412

    
413
    /// <summary>
414
    /// XSLT 2.0 transformation with source document and stylesheet supplied as URIs
415
    /// </summary>
416

    
417
    public class XsltSimple1 : Example
418
    {
419

    
420
        public override String testName
421
        {
422
            get { return "XsltSimple1"; }
423
        }
424

    
425
        public override void run(Uri samplesDir)
426
        {
427
            // Create a Processor instance.
428
            Processor processor = new Processor();
429

    
430
            // Load the source document
431
            XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/books.xml"));
432

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

    
436
            // Set the root node of the source document to be the initial context node
437
            transformer.InitialContextNode = input;
438

    
439
            // Create a serializer, with output to the standard output stream
440
            Serializer serializer = new Serializer();
441
            serializer.SetOutputWriter(Console.Out);
442

    
443
            // Transform the source XML and serialize the result document
444
            transformer.Run(serializer);
445
        }
446
    }
447

    
448
    /// <summary>
449
    /// Run a transformation, sending the serialized output to a file
450
    /// </summary>
451

    
452
    public class XsltSimple2 : Example
453
    {
454

    
455
        public override String testName
456
        {
457
            get { return "XsltSimple2"; }
458
        }
459

    
460
        public override void run(Uri samplesDir)
461
        {
462
            // Create a Processor instance.
463
            Processor processor = new Processor();
464

    
465
            // Load the source document
466
            XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/books.xml"));
467

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

    
471
            // Set the root node of the source document to be the initial context node
472
            transformer.InitialContextNode = input;
473

    
474
            // Create a serializer
475
            String outfile = "OutputFromXsltSimple2.xml";
476
            Serializer serializer = new Serializer();
477
            serializer.SetOutputStream(new FileStream(outfile, FileMode.Create, FileAccess.Write));
478

    
479
			// Transform the source XML and serialize the result to the output file.
480
            transformer.Run(serializer);
481

    
482
            Console.WriteLine("\nOutput written to " + outfile + "\n");
483
        }
484
    }
485

    
486
    /// <summary>
487
    /// XSLT 2.0 transformation with source document and stylesheet supplied as files
488
    /// </summary>
489

    
490
    public class XsltSimple3 : Example
491
    {
492

    
493
        public override String testName
494
        {
495
            get { return "XsltSimple3"; }
496
        }
497

    
498
        public override void run(Uri samplesDir)
499
        {
500
            if (samplesDir.Scheme != Uri.UriSchemeFile)
501
            {
502
                Console.WriteLine("Supplied URI must be a file directory");
503
            }
504
            String dir = samplesDir.AbsolutePath;
505
            String sourceFile = dir + "data/books.xml";
506
            String styleFile = dir + "styles/books.xsl";
507

    
508
            // Create a Processor instance.
509
            Processor processor = new Processor();
510

    
511
            // Load the source document
512
            DocumentBuilder builder = processor.NewDocumentBuilder();
513
            builder.BaseUri = new Uri(samplesDir, "data/books.xml");
514

    
515
            XdmNode input = builder.Build(File.OpenRead(sourceFile));
516

    
517
            // Create a transformer for the stylesheet.
518
            XsltCompiler compiler = processor.NewXsltCompiler();
519
            compiler.BaseUri = new Uri(samplesDir, "styles/books.xsl");
520
            XsltTransformer transformer = compiler.Compile(File.OpenRead(styleFile)).Load();
521

    
522
            // Set the root node of the source document to be the initial context node
523
            transformer.InitialContextNode = input;
524

    
525
            // Create a serializer, with output to the standard output stream
526
            Serializer serializer = new Serializer();
527
            serializer.SetOutputWriter(Console.Out);
528

    
529
            // Transform the source XML and serialize the result document
530
            transformer.Run(serializer);
531
        }
532
    }
533

    
534

    
535
    /// <summary>
536
    /// XSLT 2.0 transformation showing stripping of whitespace controlled by the stylesheet
537
    /// </summary>
538

    
539
    public class XsltStripSpace : Example
540
    {
541

    
542
        public override String testName
543
        {
544
            get { return "XsltStripSpace"; }
545
        }
546

    
547
        public override void run(Uri samplesDir)
548
        {
549
            Processor processor = new Processor();
550

    
551
            // Load the source document
552
            DocumentBuilder builder = processor.NewDocumentBuilder();
553
            builder.BaseUri = samplesDir;
554

    
555
            String doc = "<doc>  <a>  <b>text</b>  </a>  <a/>  </doc>";
556
            MemoryStream ms = new MemoryStream();
557
            StreamWriter tw = new StreamWriter(ms);
558
            tw.Write(doc);
559
            tw.Flush();
560
            Stream instr = new MemoryStream(ms.GetBuffer(), 0, (int)ms.Length);
561
            XdmNode input = builder.Build(instr);
562

    
563
            // Create a transformer for the stylesheet.
564
            String stylesheet =
565
                "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0'>" +
566
                "<xsl:strip-space elements='*'/>" +
567
                "<xsl:template match='/'>" +
568
                "  <xsl:copy-of select='.'/>" +
569
                "</xsl:template>" +
570
                "</xsl:stylesheet>";
571

    
572
            XsltCompiler compiler = processor.NewXsltCompiler();
573
            compiler.BaseUri = samplesDir;
574
            XsltTransformer transformer = compiler.Compile(new XmlTextReader(new StringReader(stylesheet))).Load();
575

    
576
            // Set the root node of the source document to be the initial context node
577
            transformer.InitialContextNode = input;
578

    
579
			// Create a serializer, with output to the standard output stream
580
            Serializer serializer = new Serializer();
581
            serializer.SetOutputWriter(Console.Out);
582

    
583
			// Transform the source XML and serialize the result document
584
            transformer.Run(serializer);
585
        }
586
    }
587

    
588

    
589
	/// <summary>
590
	/// Run a transformation, compiling the stylesheet once (into an XsltExecutable) and using it to transform two 
591
	/// different source documents
592
	/// </summary>
593

    
594
    public class XsltReuseExecutable : Example
595
    {
596

    
597
        public override String testName
598
        {
599
            get { return "XsltReuseExecutable"; }
600
        }
601

    
602
        public override void run(Uri samplesDir)
603
        {
604
            // Create a Processor instance.
605
            Processor processor = new Processor();
606

    
607
            // Create a compiled stylesheet
608
            XsltExecutable templates = processor.NewXsltCompiler().Compile(new Uri(samplesDir, "styles/summarize.xsl"));
609

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

    
613
            String sourceFile1 = "data/books.xml";
614
            String sourceFile2 = "data/othello.xml";
615

    
616
            // Do the first transformation
617
            Console.WriteLine("\n\n----- transform of " + sourceFile1 + " -----");
618
            XsltTransformer transformer1 = templates.Load();
619
            transformer1.InitialContextNode = processor.NewDocumentBuilder().Build(new Uri(samplesDir, sourceFile1));
620
            transformer1.Run(new Serializer());     // default destination is Console.Out
621

    
622
            // Do the second transformation
623
            Console.WriteLine("\n\n----- transform of " + sourceFile2 + " -----");
624
            XsltTransformer transformer2 = templates.Load();
625
            transformer2.InitialContextNode = processor.NewDocumentBuilder().Build(new Uri(samplesDir, sourceFile2));
626
            transformer2.Run(new Serializer());     // default destination is Console.Out    
627
        }
628
    }
629

    
630
    /// <summary>
631
    /// Show that the XsltTransformer is serially reusable; run a transformation twice using the same stylesheet
632
    /// and the same input document but with different parameters.
633
    /// </summary>
634

    
635
    public class XsltReuseTransformer : Example
636
    {
637

    
638
        public override String testName
639
        {
640
            get { return "XsltReuseTransformer"; }
641
        }
642

    
643
        public override void run(Uri samplesDir)
644
        {
645
            // Create a Processor instance.
646
            Processor processor = new Processor();
647

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

    
651
            // Compile the stylesheet
652
            XsltExecutable exec = processor.NewXsltCompiler().Compile(new Uri(samplesDir, "styles/summarize.xsl"));
653

    
654
            // Create a transformer 
655
            XsltTransformer transformer = exec.Load();
656

    
657
            // Run it once        
658
            transformer.SetParameter(new QName("", "", "include-attributes"), new XdmAtomicValue(false));
659
            transformer.InitialContextNode = input;
660
            XdmDestination results = new XdmDestination();
661
            transformer.Run(results);
662
            Console.WriteLine("1: " + results.XdmNode.OuterXml);
663

    
664
            // Run it again        
665
            transformer.SetParameter(new QName("", "", "include-attributes"), new XdmAtomicValue(true));
666
            transformer.InitialContextNode = input;
667
            results.Reset();
668
            transformer.Run(results);
669
            Console.WriteLine("2: " + results.XdmNode.OuterXml);
670
        }
671
    }
672

    
673
    /// <summary>
674
    /// Run a sequence of transformations in a pipeline, each one acting as a filter
675
    /// </summary>
676

    
677
    public class XsltFilterChain : Example
678
    {
679

    
680
        public override String testName
681
        {
682
            get { return "XsltFilterChain"; }
683
        }
684

    
685
        public override void run(Uri samplesDir)
686
        {
687
            // Create a Processor instance.
688
            Processor processor = new Processor();
689

    
690
            // Load the source document
691
            XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/books.xml"));
692

    
693
            // Create a compiler
694
            XsltCompiler compiler = processor.NewXsltCompiler();
695

    
696
            // Compile all three stylesheets
697
            XsltTransformer transformer1 = compiler.Compile(new Uri(samplesDir, "styles/identity.xsl")).Load();
698
            XsltTransformer transformer2 = compiler.Compile(new Uri(samplesDir, "styles/books.xsl")).Load();
699
            XsltTransformer transformer3 = compiler.Compile(new Uri(samplesDir, "styles/summarize.xsl")).Load();
700

    
701
            // Now run them in series
702
            transformer1.InitialContextNode = input;
703
            XdmDestination results1 = new XdmDestination();
704
            transformer1.Run(results1);
705
            //Console.WriteLine("After phase 1:");
706
            //Console.WriteLine(results1.XdmNode.OuterXml);
707

    
708
            transformer2.InitialContextNode = results1.XdmNode;
709
            XdmDestination results2 = new XdmDestination();
710
            transformer2.Run(results2);
711
            //Console.WriteLine("After phase 2:");
712
            //Console.WriteLine(results2.XdmNode.OuterXml);
713

    
714
            transformer3.InitialContextNode = results2.XdmNode;
715
            XdmDestination results3 = new XdmDestination();
716
            transformer3.Run(results3);
717
            Console.WriteLine("After phase 3:");
718
            Console.WriteLine(results3.XdmNode.OuterXml);
719
        }
720
    }
721

    
722
    /// <summary>
723
    /// Transform from an XDM tree to an XDM tree
724
    /// </summary>
725

    
726
    public class XsltXdmToXdm : Example
727
    {
728

    
729
        public override String testName
730
        {
731
            get { return "XsltXdmToXdm"; }
732
        }
733

    
734
        public override void run(Uri samplesDir)
735
        {
736
            // Create a Processor instance.
737
            Processor processor = new Processor();
738

    
739
            // Load the source document
740
            XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/books.xml"));
741

    
742
            // Create a compiler
743
            XsltCompiler compiler = processor.NewXsltCompiler();
744

    
745
            // Compile the stylesheet
746
            XsltTransformer transformer = compiler.Compile(new Uri(samplesDir, "styles/summarize.xsl")).Load();
747

    
748
            // Run the transformation
749
            transformer.InitialContextNode = input;
750
            XdmDestination result = new XdmDestination();
751
            transformer.Run(result);
752

    
753
            // Serialize the result so we can see that it worked
754
            StringWriter sw = new StringWriter();
755
            result.XdmNode.WriteTo(new XmlTextWriter(sw));
756
            Console.WriteLine(sw.ToString());
757

    
758
            // Note: we don't do 
759
            //   result.XdmNode.WriteTo(new XmlTextWriter(Console.Out));
760
            // because that results in the Console.out stream being closed, 
761
            // with subsequent attempts to write to it being rejected.
762
        }
763
    }
764

    
765
    /// <summary>
766
    /// Run an XSLT transformation from an Xdm tree, starting at a node that is not the document node
767
    /// </summary>
768

    
769
    public class XsltXdmElementToXdm : Example
770
    {
771

    
772
        public override String testName
773
        {
774
            get { return "XsltXdmElementToXdm"; }
775
        }
776

    
777
        public override void run(Uri samplesDir)
778
        {
779
            // Create a Processor instance.
780
            Processor processor = new Processor();
781

    
782
            // Load the source document
783
            XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/othello.xml"));
784

    
785
            // Navigate to the first grandchild
786
            XPathSelector eval = processor.NewXPathCompiler().Compile("/PLAY/FM[1]").Load();
787
            eval.ContextItem = input;
788
            input = (XdmNode)eval.EvaluateSingle();
789

    
790
            // Create an XSLT compiler
791
            XsltCompiler compiler = processor.NewXsltCompiler();
792

    
793
            // Compile the stylesheet
794
            XsltTransformer transformer = compiler.Compile(new Uri(samplesDir, "styles/summarize.xsl")).Load();
795

    
796
            // Run the transformation
797
            transformer.InitialContextNode = input;
798
            XdmDestination result = new XdmDestination();
799
            transformer.Run(result);
800

    
801
            // Serialize the result so we can see that it worked
802
            Console.WriteLine(result.XdmNode.OuterXml);
803
        }
804
    }
805

    
806
    /// <summary>
807
    /// Run a transformation from a DOM (System.Xml.Document) input to a DOM output
808
    /// </summary>
809

    
810
    public class XsltDomToDom : Example
811
    {
812

    
813
        public override String testName
814
        {
815
            get { return "XsltDomToDom"; }
816
        }
817

    
818
        public override void run(Uri samplesDir)
819
        {
820
            // Create a Processor instance.
821
            Processor processor = new Processor();
822

    
823
            // Load the source document (in practice, it would already exist as a DOM)
824
            XmlDocument doc = new XmlDocument();
825
            doc.Load(new XmlTextReader(samplesDir.AbsolutePath + "data/othello.xml"));
826
            XdmNode input = processor.NewDocumentBuilder().Wrap(doc);
827

    
828
            // Create a compiler
829
            XsltCompiler compiler = processor.NewXsltCompiler();
830

    
831
            // Compile the stylesheet
832
            XsltTransformer transformer = compiler.Compile(new Uri(samplesDir, "styles/summarize.xsl")).Load();
833

    
834
            // Run the transformation
835
            transformer.InitialContextNode = input;
836
            DomDestination result = new DomDestination();
837
            transformer.Run(result);
838

    
839
            // Serialize the result so we can see that it worked
840
            Console.WriteLine(result.XmlDocument.OuterXml);
841
        }
842
    }
843

    
844

    
845
    /// <summary>
846
    /// Run a transformation driven by an xml-stylesheet processing instruction in the source document
847
    /// </summary>
848

    
849
    public class XsltProcessingInstruction : Example
850
    {
851

    
852
        public override string testName
853
        {
854
            get { return "XsltProcessingInstruction"; }
855
        }
856

    
857
        public override void run(Uri samplesDir)
858
        {
859
            // Create a Processor instance.
860
            Processor processor = new Processor();
861
            XsltExecutable exec;
862

    
863
            // Load the source document
864
            XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/books.xml"));
865
            //Console.WriteLine("=============== source document ===============");
866
            //Console.WriteLine(input.OuterXml);
867
            //Console.WriteLine("=========== end of source document ============");
868

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

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

    
875
            XPathSelector eval = processor.NewXPathCompiler().Compile(path).Load();
876
            eval.ContextItem = input;
877
            XdmAtomicValue hrefval = (XdmAtomicValue)eval.EvaluateSingle();
878
            String href = (hrefval == null ? null : hrefval.ToString());
879

    
880
            if (href == null || href == "")
881
            {
882
                Console.WriteLine("No suitable xml-stylesheet processing instruction found");
883
                return;
884

    
885
            }
886
            else if (href[0] == '#')
887
            {
888

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

    
891
                Console.WriteLine("Locating embedded stylesheet with href = " + href);
892
                String idpath = "id('" + href.Substring(1) + "')";
893
                eval = processor.NewXPathCompiler().Compile(idpath).Load();
894
                eval.ContextItem = input;
895
                XdmNode node = (XdmNode)eval.EvaluateSingle();
896
                if (node == null)
897
                {
898
                    Console.WriteLine("No element found with ID " + href.Substring(1));
899
                    return;
900
                }
901
                exec = processor.NewXsltCompiler().Compile(node);
902

    
903
            }
904
            else
905
            {
906

    
907
                // The stylesheet is in an external document
908

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

    
911
                // Fetch and compile the referenced stylesheet
912
                exec = processor.NewXsltCompiler().Compile(new Uri(input.BaseUri, href.ToString()));
913
            }
914

    
915
            // Create a transformer 
916
            XsltTransformer transformer = exec.Load();
917

    
918
            // Run it       
919
            transformer.InitialContextNode = input;
920
            XdmDestination results = new XdmDestination();
921
            transformer.Run(results);
922
            Console.WriteLine(results.XdmNode.OuterXml);
923

    
924
        }
925
    }
926

    
927
    /// <summary>
928
    /// Run an XSLT transformation setting serialization properties from the calling application
929
    /// </summary>
930

    
931
    public class XsltSettingOutputProperties : Example
932
    {
933

    
934
        public override string testName
935
        {
936
            get { return "XsltSettingOutputProperties"; }
937
        }
938

    
939
        public override void run(Uri samplesDir)
940
        {
941
            // Create a Processor instance.
942
            Processor processor = new Processor();
943

    
944
            // Load the source document
945
            XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/books.xml"));
946

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

    
950
            // Set the root node of the source document to be the initial context node
951
            transformer.InitialContextNode = input;
952

    
953
            // Create a serializer, with output to the standard output stream
954
            Serializer serializer = new Serializer();
955
            serializer.SetOutputProperty(Serializer.METHOD, "xml");
956
            serializer.SetOutputProperty(Serializer.INDENT, "no");
957
            serializer.SetOutputWriter(Console.Out);
958

    
959
            // Transform the source XML and serialize the result document
960
            transformer.Run(serializer);
961
        }
962

    
963
    }
964

    
965
    /// <summary>
966
    /// Run an XSLT transformation making use of an XmlResolver to resolve URIs at document build time, at stylesheet compile time 
967
    /// and at transformation run-time
968
    /// </summary>
969

    
970
    public class XsltUsingSourceResolver : Example
971
    {
972

    
973
        public override string testName
974
        {
975
            get { return "XsltUsingSourceResolver"; }
976
        }
977

    
978
        public override void run(Uri samplesDir)
979
        {
980

    
981
            // Create a Processor instance.
982
            Processor processor = new Processor();
983

    
984
            // Load the source document
985
            DocumentBuilder builder = processor.NewDocumentBuilder();
986
            UserXmlResolver buildTimeResolver = new UserXmlResolver();
987
            buildTimeResolver.Message = "** Calling build-time XmlResolver: ";
988
            builder.XmlResolver = buildTimeResolver;
989
            builder.BaseUri = samplesDir;
990

    
991
            String doc = "<!DOCTYPE doc [<!ENTITY e SYSTEM 'flamingo.txt'>]><doc>&e;</doc>";
992
            MemoryStream ms = new MemoryStream();
993
            StreamWriter tw = new StreamWriter(ms);
994
            tw.Write(doc);
995
            tw.Flush();
996
            Stream instr = new MemoryStream(ms.GetBuffer(), 0, (int)ms.Length);
997
            XdmNode input = builder.Build(instr);
998

    
999
            // Create a transformer for the stylesheet.
1000
            String stylesheet =
1001
                "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0'>" +
1002
                "<xsl:import href='empty.xslt'/>" +
1003
                "<xsl:template match='/'>" +
1004
                "<out note=\"{doc('heron.txt')}\" ><xsl:copy-of select='.'/></out>" +
1005
                "</xsl:template>" +
1006
                "</xsl:stylesheet>";
1007

    
1008
            XsltCompiler compiler = processor.NewXsltCompiler();
1009
            UserXmlResolver compileTimeResolver = new UserXmlResolver();
1010
            compileTimeResolver.Message = "** Calling compile-time XmlResolver: ";
1011
            compiler.XmlResolver = compileTimeResolver;
1012
            compiler.BaseUri = samplesDir;
1013
            XsltTransformer transformer = compiler.Compile(new XmlTextReader(new StringReader(stylesheet))).Load();
1014

    
1015
            // Set the root node of the source document to be the initial context node
1016
            transformer.InitialContextNode = input;
1017

    
1018
            // Set the user-written XmlResolver
1019
            UserXmlResolver runTimeResolver = new UserXmlResolver();
1020
            runTimeResolver.Message = "** Calling transformation-time XmlResolver: ";
1021
            transformer.InputXmlResolver = runTimeResolver;
1022

    
1023
            // Create a serializer
1024
            Serializer serializer = new Serializer();
1025
            serializer.SetOutputWriter(Console.Out);
1026

    
1027
			// Transform the source XML and serialize the result document
1028
            transformer.Run(serializer);
1029

    
1030
        }
1031
    }
1032

    
1033
    /// <summary>
1034
    /// Run an XSLT transformation displaying compile-time errors to the console
1035
    /// </summary>
1036

    
1037
    public class XsltDisplayingErrors : Example
1038
    {
1039

    
1040
        public override string testName
1041
        {
1042
            get { return "XsltDisplayingErrors"; }
1043
        }
1044

    
1045
        public override void run(Uri samplesDir)
1046
        {
1047
            // Create a Processor instance.
1048
            Processor processor = new Processor();
1049

    
1050
            // Create the XSLT Compiler
1051
            XsltCompiler compiler = processor.NewXsltCompiler();
1052

    
1053

    
1054
            // Define a stylesheet containing errors
1055
            String stylesheet =
1056
                "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0'>\n" +
1057
                "<xsl:template name='eee:template'>\n" +
1058
                "  <xsl:value-of select='32'/>\n" +
1059
                "</xsl:template>\n" +
1060
                "<xsl:template name='main'>\n" +
1061
                "  <xsl:value-of select='$var'/>\n" +
1062
                "</xsl:template>\n" +
1063
                "</xsl:stylesheet>";
1064

    
1065

    
1066
            // Attempt to compile the stylesheet and display the errors
1067
            try
1068
            {
1069
                compiler.BaseUri = new Uri("http://localhost/stylesheet");
1070
                compiler.Compile(new XmlTextReader(new StringReader(stylesheet)));
1071
                Console.WriteLine("Stylesheet compilation succeeded");
1072
            }
1073
            catch (Exception)
1074
            {
1075
                Console.WriteLine("Stylesheet compilation failed");
1076
            }
1077

    
1078

    
1079
        }
1080
    }
1081

    
1082
    /// <summary>
1083
    /// Run an XSLT transformation capturing compile-time errors within the application
1084
    /// </summary>
1085

    
1086
    public class XsltCapturingErrors : Example
1087
    {
1088

    
1089
        public override string testName
1090
        {
1091
            get { return "XsltCapturingErrors"; }
1092
        }
1093

    
1094
        public override void run(Uri samplesDir)
1095
        {
1096
            // Create a Processor instance.
1097
            Processor processor = new Processor();
1098

    
1099
            // Create the XSLT Compiler
1100
            XsltCompiler compiler = processor.NewXsltCompiler();
1101

    
1102
            // Create a list to hold the error information
1103
            compiler.ErrorList = new ArrayList();
1104

    
1105
            // Define a stylesheet containing errors
1106
            String stylesheet =
1107
                "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0'>\n" +
1108
                "<xsl:template name='fff:template'>\n" +
1109
                "  <xsl:value-of select='32'/>\n" +
1110
                "</xsl:template>\n" +
1111
                "<xsl:template name='main'>\n" +
1112
                "  <xsl:value-of select='$var'/>\n" +
1113
                "</xsl:template>\n" +
1114
                "</xsl:stylesheet>";
1115

    
1116

    
1117
            // Attempt to compile the stylesheet and display the errors
1118
            try
1119
            {
1120
                compiler.BaseUri = new Uri("http://localhost/stylesheet");
1121
                compiler.Compile(new StringReader(stylesheet));
1122
                Console.WriteLine("Stylesheet compilation succeeded");
1123
            }
1124
            catch (Exception)
1125
            {
1126
                Console.WriteLine("Stylesheet compilation failed with " + compiler.ErrorList.Count + " errors");
1127
                foreach (StaticError error in compiler.ErrorList)
1128
                {
1129
                    Console.WriteLine("At line " + error.LineNumber + ": " + error.Message);
1130
                }
1131
            }
1132
        }
1133
    }
1134

    
1135
    /// <summary>
1136
    /// Run an XSLT transformation capturing run-time messages within the application
1137
    /// </summary>
1138

    
1139
    public class XsltCapturingMessages : Example
1140
    {
1141

    
1142
        public override string testName
1143
        {
1144
            get { return "XsltCapturingMessages"; }
1145
        }
1146

    
1147
        public override void run(Uri samplesDir)
1148
        {
1149

    
1150
            // Create a Processor instance.
1151
            Processor processor = new Processor();
1152

    
1153
            // Create the XSLT Compiler
1154
            XsltCompiler compiler = processor.NewXsltCompiler();
1155

    
1156
            // Define a stylesheet that generates messages
1157
            String stylesheet =
1158
                "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0'>\n" +
1159
                "<xsl:template name='main'>\n" +
1160
                "  <xsl:message><a>starting</a></xsl:message>\n" +
1161
                "  <out><xsl:value-of select='current-date()'/></out>\n" +
1162
                "  <xsl:message><a>finishing</a></xsl:message>\n" +
1163
                "</xsl:template>\n" +
1164
                "</xsl:stylesheet>";
1165

    
1166
            compiler.BaseUri = new Uri("http://localhost/stylesheet");
1167
            XsltExecutable exec = compiler.Compile(new StringReader(stylesheet));
1168

    
1169

    
1170
            // Create a transformer for the stylesheet.
1171
            XsltTransformer transformer = exec.Load();
1172

    
1173
            // Set the name of the initial template
1174
            transformer.InitialTemplate = new QName("", "main");
1175

    
1176
            // Create a Listener to which messages will be written
1177
            transformer.MessageListener = new UserMessageListener();
1178

    
1179
			// Create a serializer, with output to the standard output stream
1180
            Serializer serializer = new Serializer();
1181
            serializer.SetOutputWriter(Console.Out);
1182

    
1183
			// Transform the source XML and serialize the result document
1184
            transformer.Run(serializer);
1185
        }
1186

    
1187
    }
1188

    
1189
    ///
1190
    /// Example user-written message listener
1191
    ///
1192

    
1193
    public class UserMessageListener : IMessageListener
1194
    {
1195

    
1196
        public void Message(XdmNode content, bool terminate, IXmlLocation location)
1197
        {
1198
            Console.Out.WriteLine("MESSAGE terminate=" + (terminate ? "yes" : "no") + " at " + DateTime.Now);
1199
            Console.Out.WriteLine("From instruction at line " + location.LineNumber +
1200
                    " of " + location.BaseUri);
1201
            Console.Out.WriteLine(">>" + content.StringValue);
1202
        }
1203
    }
1204

    
1205

    
1206
    /// <summary>
1207
    /// Run an XSLT transformation producing multiple output documents
1208
    /// </summary>
1209

    
1210
    public class XsltMultipleOutput : Example
1211
    {
1212

    
1213
        public override string testName
1214
        {
1215
            get { return "XsltMultipleOutput"; }
1216
        }
1217

    
1218
        public override void run(Uri samplesDir)
1219
        {
1220
            // Create a Processor instance.
1221
            Processor processor = new Processor();
1222
            processor.SetProperty("http://saxon.sf.net/feature/timing", "true");
1223

    
1224
            // Load the source document
1225
            XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/othello.xml"));
1226

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

    
1230
            // Set the root node of the source document to be the initial context node
1231
            transformer.InitialContextNode = input;
1232

    
1233
            // Set the required stylesheet parameter
1234
            transformer.SetParameter(new QName("", "", "dir"), new XdmAtomicValue(samplesDir.ToString() + "play"));
1235

    
1236
			// Create a serializer, with output to the standard output stream
1237
            Serializer serializer = new Serializer();
1238
            serializer.SetOutputWriter(Console.Out);
1239

    
1240
			// Transform the source XML and serialize the result document
1241
            transformer.Run(serializer);
1242

    
1243
        }
1244

    
1245
    }
1246

    
1247

    
1248
    /// <summary>
1249
    /// Run an XSLT transformation using the id() function, with DTD validation
1250
    /// </summary>
1251

    
1252
    public class XsltUsingIdFunction : Example
1253
    {
1254

    
1255
        public override string testName
1256
        {
1257
            get { return "XsltUsingIdFunction"; }
1258
        }
1259

    
1260
        public override void run(Uri samplesDir)
1261
        {
1262
            // Create a Processor instance
1263
            Processor processor = new Processor();
1264

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

    
1269
            String doc = "<!DOCTYPE table [" +
1270
                "<!ELEMENT table (row*)>" +
1271
                "<!ELEMENT row EMPTY>" +
1272
                "<!ATTLIST row xml:id ID #REQUIRED>" +
1273
                "<!ATTLIST row value CDATA #REQUIRED>]>" +
1274
                "<table><row xml:id='A123' value='green'/><row xml:id='Z789' value='blue'/></table>";
1275

    
1276
            DocumentBuilder builder = processor.NewDocumentBuilder();
1277
            builder.DtdValidation = true;
1278
            builder.BaseUri = samplesDir;
1279
            MemoryStream ms = new MemoryStream();
1280
            StreamWriter tw = new StreamWriter(ms);
1281
            tw.Write(doc);
1282
            tw.Flush();
1283
            Stream instr = new MemoryStream(ms.GetBuffer(), 0, (int)ms.Length);
1284
            XdmNode input = builder.Build(instr);
1285

    
1286
            // Define a stylesheet that uses the id() function
1287
            String stylesheet =
1288
                "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0'>\n" +
1289
                "<xsl:template match='/'>\n" +
1290
                "  <xsl:copy-of select=\"id('Z789')\"/>\n" +
1291
                "</xsl:template>\n" +
1292
                "</xsl:stylesheet>";
1293

    
1294
            XsltCompiler compiler = processor.NewXsltCompiler();
1295
            compiler.BaseUri = new Uri("http://localhost/stylesheet");
1296
            XsltExecutable exec = compiler.Compile(new StringReader(stylesheet));
1297

    
1298
            // Create a transformer for the stylesheet
1299
            XsltTransformer transformer = exec.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 destination
1305
            XdmDestination results = new XdmDestination();
1306

    
1307
            // Transform the XML
1308
            transformer.Run(results);
1309

    
1310
            // Show the result
1311
            Console.WriteLine(results.XdmNode.ToString());
1312

    
1313
        }
1314

    
1315
    }
1316

    
1317
    /// <summary>
1318
    /// Show a transformation using a user-written result document handler. This example
1319
    /// captures each of the result documents in a DOM, and creates a Hashtable that indexes
1320
    /// the DOM trees according to their absolute URI. On completion, it writes all the DOMs
1321
    /// to the standard output.
1322
    /// </summary>
1323

    
1324
    public class XsltUsingResultHandler : Example
1325
    {
1326

    
1327
        public override string testName
1328
        {
1329
            get { return "XsltUsingResultHandler"; }
1330
        }
1331

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

    
1337
            // Load the source document
1338
            XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/othello.xml"));
1339

    
1340
            // Define a stylesheet that splits the document up
1341
            String stylesheet =
1342
                "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0'>\n" +
1343
                "<xsl:template match='/'>\n" +
1344
                "  <xsl:for-each select='//ACT'>\n" +
1345
                "    <xsl:result-document href='{position()}.xml'>\n" +
1346
                "      <xsl:copy-of select='TITLE'/>\n" +
1347
                "    </xsl:result-document>\n" +
1348
                "  </xsl:for-each>\n" +
1349
                "</xsl:template>\n" +
1350
                "</xsl:stylesheet>";
1351

    
1352
            XsltCompiler compiler = processor.NewXsltCompiler();
1353
            compiler.BaseUri = new Uri("http://localhost/stylesheet");
1354
            XsltExecutable exec = compiler.Compile(new StringReader(stylesheet));
1355

    
1356
            // Create a transformer for the stylesheet.
1357
            XsltTransformer transformer = exec.Load();
1358

    
1359
            // Set the root node of the source document to be the initial context node
1360
            transformer.InitialContextNode = input;
1361

    
1362
            // Establish the result document handler
1363
            Hashtable results = new Hashtable();
1364
            transformer.ResultDocumentHandler = new UserResultDocumentHandler(results);
1365

    
1366
            // Transform the source XML to a NullDestination (because we only want the secondary result files).
1367
            transformer.Run(new NullDestination());
1368

    
1369
            // Process the captured DOM results
1370
            foreach (DictionaryEntry entry in results)
1371
            {
1372
                string uri = (string)entry.Key;
1373
                Console.WriteLine("\nResult File " + uri);
1374
                DomDestination dom = (DomDestination)results[uri];
1375
                Console.Write(dom.XmlDocument.OuterXml);
1376
            }
1377

    
1378
        }
1379

    
1380
    }
1381

    
1382
    /// <summary>
1383
    /// Show a transformation using a registered collection
1384
    /// </summary>
1385

    
1386
    public class XsltUsingRegisteredCollection : Example
1387
    {
1388

    
1389
        public override string testName
1390
        {
1391
            get { return "XsltUsingRegisteredCollection"; }
1392
        }
1393

    
1394
        public override void run(Uri samplesDir)
1395
        {
1396
            // Create a Processor instance.
1397
            Processor processor = new Processor();
1398

    
1399
			// Define a stylesheet that uses the collection() function
1400
            String stylesheet =
1401
                "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0'>\n" +
1402
                "<xsl:template name='main'>\n" +
1403
                " <out>\n" +
1404
                "  <xsl:for-each select=\"collection('http://www.example.org/my-collection')\">\n" +
1405
                "    <document uri='{document-uri(.)}' nodes='{count(//*)}'/>\n" +
1406
                "  </xsl:for-each><zzz/>\n" +
1407
                "  <xsl:for-each select=\"collection('http://www.example.org/my-collection')\">\n" +
1408
                "    <document uri='{document-uri(.)}' nodes='{count(//*)}'/>\n" +
1409
                "  </xsl:for-each>\n" +
1410
                " </out>\n" +
1411
                "</xsl:template>\n" +
1412
                "</xsl:stylesheet>";
1413

    
1414
			// Register a named collection
1415
            Uri[] documentList = new Uri[2];
1416
            documentList[0] = new Uri(samplesDir, "data/othello.xml");
1417
            documentList[1] = new Uri(samplesDir, "data/books.xml");
1418
            processor.RegisterCollection(new Uri("http://www.example.org/my-collection"), documentList);
1419

    
1420
            XsltCompiler compiler = processor.NewXsltCompiler();
1421
            compiler.BaseUri = new Uri("http://localhost/stylesheet");
1422
            XsltExecutable exec = compiler.Compile(new StringReader(stylesheet));
1423

    
1424
            // Create a transformer for the stylesheet.
1425
            XsltTransformer transformer = exec.Load();
1426

    
1427
			// Set the name of the initial template
1428
            transformer.InitialTemplate = new QName("", "main");
1429

    
1430
            // Set the destination
1431
            XdmDestination results = new XdmDestination();
1432

    
1433
            // Transform the XML
1434
            transformer.Run(results);
1435

    
1436
            // Show the result
1437
            Console.WriteLine(results.XdmNode.ToString());
1438

    
1439
        }
1440
    }
1441

    
1442
    /// <summary>
1443
	/// Show a transformation using a collection that maps to a directory
1444
    /// </summary>
1445

    
1446
    public class XsltUsingDirectoryCollection : Example
1447
    {
1448

    
1449
        public override string testName
1450
        {
1451
            get { return "XsltUsingDirectoryCollection"; }
1452
        }
1453

    
1454
        public override void run(Uri samplesDir)
1455
        {
1456
            // Create a Processor instance.
1457
            Processor processor = new Processor();
1458

    
1459
			// Define a stylesheet that uses the collection() function
1460
            String stylesheet =
1461
                "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0'>\n" +
1462
                "<xsl:template name='main'>\n" +
1463
                " <out>\n" +
1464
                "  <xsl:for-each select=\"collection('" + samplesDir + "?recurse=yes;select=*.xml;on-error=warning')\">\n" +
1465
                "    <document uri='{document-uri(.)}' nodes='{count(//*)}'/>\n" +
1466
                "  </xsl:for-each><zzz/>\n" +
1467
                " </out>\n" +
1468
                "</xsl:template>\n" +
1469
                "</xsl:stylesheet>";
1470

    
1471

    
1472
            XsltCompiler compiler = processor.NewXsltCompiler();
1473
            compiler.BaseUri = new Uri("http://localhost/stylesheet");
1474
            XsltExecutable exec = compiler.Compile(new StringReader(stylesheet));
1475

    
1476
            // Create a transformer for the stylesheet.
1477
            XsltTransformer transformer = exec.Load();
1478

    
1479
			// Set the name of the initial template
1480
            transformer.InitialTemplate = new QName("", "main");
1481

    
1482
            // Set the destination
1483
            XdmDestination results = new XdmDestination();
1484

    
1485
            // Transform the XML
1486
            transformer.Run(results);
1487

    
1488
            // Show the result
1489
            Console.WriteLine(results.XdmNode.ToString());
1490

    
1491
        }
1492

    
1493
    }
1494

    
1495

    
1496

    
1497
    /// <summary>
1498
    /// Show a transformation using calls to extension functions
1499
    /// </summary>
1500

    
1501
    public class XsltIntegratedExtension : Example
1502
    {
1503

    
1504
        public override string testName
1505
        {
1506
            get { return "XsltIntegratedExtension"; }
1507
        }
1508

    
1509
        public override void run(Uri samplesDir)
1510
        {
1511

    
1512
            // Create a Processor instance.
1513
            Processor processor = new Processor();
1514

    
1515
            // Identify the Processor version
1516
            Console.WriteLine(processor.ProductVersion);
1517

    
1518
            // Set diagnostics
1519
            //processor.SetProperty("http://saxon.sf.net/feature/trace-external-functions", "true");
1520

    
1521
            // Create the stylesheet
1522
            String s = @"<xsl:transform version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'" +
1523
                @" xmlns:math='http://example.math.co.uk/demo'> " +
1524
                @" <xsl:template name='go'> " +
1525
                @" <out sqrt2='{math:sqrt(2.0e0)}' " +
1526
                @" sqrtEmpty='{math:sqrt(())}'/> " +
1527
                @" </xsl:template></xsl:transform>";
1528

    
1529
            // Register the integrated extension function math:sqrt
1530
            processor.RegisterExtensionFunction(new Sqrt());
1531

    
1532
            // Create a transformer for the stylesheet.
1533
            XsltTransformer transformer = processor.NewXsltCompiler().Compile(new StringReader(s)).Load();
1534

    
1535
			// Set the name of the initial template
1536
            transformer.InitialTemplate = new QName("go");
1537

    
1538
			// Create a serializer, with output to the standard output stream
1539
            Serializer serializer = new Serializer();
1540
            serializer.SetOutputWriter(Console.Out);
1541
            serializer.SetOutputProperty(Serializer.INDENT, "yes");
1542

    
1543
			// Transform the source XML and serialize the result document
1544
            transformer.Run(serializer);
1545
        }
1546

    
1547
    }
1548

    
1549
    /// <summary>
1550
    /// Example extension function to compute a square root.
1551
    /// </summary>
1552

    
1553
    public class Sqrt : ExtensionFunctionDefinition
1554
    {
1555
        public override QName FunctionName
1556
        {
1557
            get
1558
            {
1559
                return new QName("http://example.math.co.uk/demo", "sqrt");
1560
            }
1561
        }
1562

    
1563
        public override int MinimumNumberOfArguments
1564
        {
1565
            get
1566
            {
1567
                return 1;
1568
            }
1569
        }
1570

    
1571
        public override int MaximumNumberOfArguments
1572
        {
1573
            get
1574
            {
1575
                return 1;
1576
            }
1577
        }
1578

    
1579
        public override XdmSequenceType[] ArgumentTypes
1580
        {
1581
            get
1582
            {
1583
                return new XdmSequenceType[]{
1584
                    new XdmSequenceType(XdmAtomicType.BuiltInAtomicType(QName.XS_DOUBLE), '?')
1585
                };
1586
            }
1587
        }
1588

    
1589
        public override XdmSequenceType ResultType(XdmSequenceType[] ArgumentTypes)
1590
        {
1591
            return new XdmSequenceType(XdmAtomicType.BuiltInAtomicType(QName.XS_DOUBLE), '?');
1592
        }
1593

    
1594
        public override bool TrustResultType
1595
        {
1596
            get
1597
            {
1598
                return true;
1599
            }
1600
        }
1601

    
1602

    
1603
        public override ExtensionFunctionCall MakeFunctionCall()
1604
        {
1605
            return new SqrtCall();
1606
        }
1607
    }
1608

    
1609
    internal class SqrtCall : ExtensionFunctionCall
1610
    {
1611
        public override IXdmEnumerator Call(IXdmEnumerator[] arguments, DynamicContext context)
1612
        {
1613
            Boolean exists = arguments[0].MoveNext();
1614
            if (exists)
1615
            {
1616
                XdmAtomicValue arg = (XdmAtomicValue)arguments[0].Current;
1617
                double val = (double)arg.Value;
1618
                double sqrt = System.Math.Sqrt(val);
1619
                XdmAtomicValue result = new XdmAtomicValue(sqrt);
1620
                return (IXdmEnumerator)result.GetEnumerator();
1621
            }
1622
            else
1623
            {
1624
                return EmptyEnumerator.INSTANCE;
1625
            }
1626
        }
1627

    
1628
    }
1629

    
1630
    /// <summary>
1631
    /// Example extension function to return the default namespace from the static context
1632
    /// </summary>
1633

    
1634
    public class DefaultNamespace : ExtensionFunctionDefinition
1635
    {
1636
        public override QName FunctionName
1637
        {
1638
            get
1639
            {
1640
                return new QName("http://example.env.co.uk/demo", "defaultNamespace");
1641
            }
1642
        }
1643

    
1644
        public override int MinimumNumberOfArguments
1645
        {
1646
            get
1647
            {
1648
                return 0;
1649
            }
1650
        }
1651

    
1652
        public override int MaximumNumberOfArguments
1653
        {
1654
            get
1655
            {
1656
                return 0;
1657
            }
1658
        }
1659

    
1660
        public override XdmSequenceType[] ArgumentTypes
1661
        {
1662
            get
1663
            {
1664
                return new XdmSequenceType[] { };
1665
            }
1666
        }
1667

    
1668
        public override bool DependsOnFocus
1669
        {
1670
            get
1671
            {
1672
                return true;
1673
                // actually it depends on the static context rather than the focus; but returning true is necessary
1674
                // to avoid the call being extracted to a global variable.
1675
            }
1676
        }
1677

    
1678
        public override XdmSequenceType ResultType(XdmSequenceType[] ArgumentTypes)
1679
        {
1680
            return new XdmSequenceType(XdmAtomicType.BuiltInAtomicType(QName.XS_STRING), '?');
1681
        }
1682

    
1683
        public override bool TrustResultType
1684
        {
1685
            get
1686
            {
1687
                return true;
1688
            }
1689
        }
1690

    
1691

    
1692
        public override ExtensionFunctionCall MakeFunctionCall()
1693
        {
1694
            return new DefaultNamespaceCall();
1695
        }
1696
    }
1697

    
1698
    internal class DefaultNamespaceCall : ExtensionFunctionCall
1699
    {
1700
        private string defaultNamespace;
1701

    
1702
        public override void SupplyStaticContext(StaticContext context)
1703
        {
1704
            defaultNamespace = context.GetNamespaceForPrefix("");
1705
        }
1706

    
1707
        public override IXdmEnumerator Call(IXdmEnumerator[] arguments, DynamicContext context)
1708
        {
1709
            if (defaultNamespace != null)
1710
            {
1711
                return (IXdmEnumerator)new XdmAtomicValue(defaultNamespace).GetEnumerator();
1712
            }
1713
            else
1714
            {
1715
                return EmptyEnumerator.INSTANCE;
1716
            }
1717
        }
1718

    
1719
    }
1720

    
1721
    /// <summary>
1722
    /// Show a query producing a document as its result and serializing this to a FileStream
1723
    /// </summary>
1724

    
1725
    public class XQueryToStream : Example
1726
    {
1727

    
1728
        public override string testName
1729
        {
1730
            get { return "XQueryToStream"; }
1731
        }
1732

    
1733
        public override void run(Uri samplesDir)
1734
        {
1735
            Processor processor = new Processor();
1736
            XQueryCompiler compiler = processor.NewXQueryCompiler();
1737
            compiler.BaseUri = samplesDir.ToString();
1738
            compiler.DeclareNamespace("saxon", "http://saxon.sf.net/");
1739
            XQueryExecutable exp = compiler.Compile("<saxon:example>{static-base-uri()}</saxon:example>");
1740
            XQueryEvaluator eval = exp.Load();
1741
            Serializer qout = new Serializer();
1742
            qout.SetOutputProperty(Serializer.METHOD, "xml");
1743
            qout.SetOutputProperty(Serializer.INDENT, "yes");
1744
            qout.SetOutputStream(new FileStream("testoutput.xml", FileMode.Create, FileAccess.Write));
1745
            Console.WriteLine("Output written to testoutput.xml");
1746
            eval.Run(qout);
1747
        }
1748

    
1749
    }
1750

    
1751
    /// <summary>
1752
    /// Show a query producing a single atomic value as its result and returning the value
1753
    /// to the C# application
1754
    /// </summary>
1755

    
1756
    public class XQueryToAtomicValue : Example
1757
    {
1758

    
1759
        public override string testName
1760
        {
1761
            get { return "XQueryToAtomicValue"; }
1762
        }
1763

    
1764
        public override void run(Uri samplesDir)
1765
        {
1766
            Processor processor = new Processor();
1767
            XQueryCompiler compiler = processor.NewXQueryCompiler();
1768
            XQueryExecutable exp = compiler.Compile("avg(for $i in 1 to 10 return $i * $i)");
1769
            XQueryEvaluator eval = exp.Load();
1770
            XdmAtomicValue result = (XdmAtomicValue)eval.EvaluateSingle();
1771
            Console.WriteLine("Result type: " + result.Value.GetType());
1772
            Console.WriteLine("Result value: " + (decimal)result.Value);
1773
        }
1774

    
1775
	}
1776

    
1777
	/// <summary>
1778
	/// Show a query producing a sequence as its result and returning the sequence
1779
	/// to the C# application in the form of an iterator. For each item in the
1780
	/// result, its string value is output.
1781
	/// </summary>
1782

    
1783
	public class XQueryToSequence : Example
1784
	{
1785

    
1786
		public override string testName
1787
		{
1788
			get { return "XQueryToSequence"; }
1789
		}
1790

    
1791
		public override void run(Uri samplesDir)
1792
		{
1793
			Processor processor = new Processor();
1794
			XQueryCompiler compiler = processor.NewXQueryCompiler();
1795
			XQueryExecutable exp = compiler.Compile("for $i in 1 to 10 return $i * $i");
1796
			XQueryEvaluator eval = exp.Load();
1797
			XdmValue value = eval.Evaluate();
1798
			IEnumerator e = value.GetEnumerator();
1799
			while (e.MoveNext())
1800
			{
1801
				XdmItem item = (XdmItem)e.Current;
1802
				Console.WriteLine(item.ToString());
1803
			}
1804

    
1805
		}
1806

    
1807
	}
1808

    
1809
    /// <summary>
1810
    /// Show a query producing a DOM as its input and producing a DOM as its output
1811
    /// </summary>
1812

    
1813
    public class XQueryToDom : Example
1814
    {
1815

    
1816
        public override string testName
1817
        {
1818
            get { return "XQueryToDom"; }
1819
        }
1820

    
1821
        public override void run(Uri samplesDir)
1822
        {
1823
            Processor processor = new Processor();
1824

    
1825
            XmlDocument input = new XmlDocument();
1826
            input.Load(new Uri(samplesDir, "data/books.xml").ToString());
1827
            XdmNode indoc = processor.NewDocumentBuilder().Build(new XmlNodeReader(input));
1828

    
1829
            XQueryCompiler compiler = processor.NewXQueryCompiler();
1830
            XQueryExecutable exp = compiler.Compile("<doc>{reverse(/*/*)}</doc>");
1831
            XQueryEvaluator eval = exp.Load();
1832
            eval.ContextItem = indoc;
1833
            DomDestination qout = new DomDestination();
1834
            eval.Run(qout);
1835
            XmlDocument outdoc = qout.XmlDocument;
1836
            Console.WriteLine(outdoc.OuterXml);
1837
        }
1838

    
1839
    }
1840

    
1841
    /// <summary>
1842
    /// Show a query producing a Saxon tree as its input and producing a Saxon tree as its output
1843
    /// </summary>
1844

    
1845
    public class XQueryToXdm : Example
1846
    {
1847

    
1848
        public override string testName
1849
        {
1850
            get { return "XQueryToXdm"; }
1851
        }
1852

    
1853
        public override void run(Uri samplesDir)
1854
        {
1855
            Processor processor = new Processor();
1856

    
1857
            DocumentBuilder loader = processor.NewDocumentBuilder();
1858
            loader.BaseUri = new Uri(samplesDir, "data/books.xml");
1859
            XdmNode indoc = loader.Build(loader.BaseUri);
1860

    
1861
            XQueryCompiler compiler = processor.NewXQueryCompiler();
1862
            XQueryExecutable exp = compiler.Compile("<doc>{reverse(/*/*)}</doc>");
1863
            XQueryEvaluator eval = exp.Load();
1864
            eval.ContextItem = indoc;
1865
            XdmDestination qout = new XdmDestination();
1866
            eval.Run(qout);
1867
            XdmNode outdoc = qout.XdmNode;
1868
            Console.WriteLine(outdoc.OuterXml);
1869
        }
1870

    
1871
    }
1872

    
1873
    /// <summary>
1874
    /// Show a query making a direct call to a user-defined function defined in the query
1875
    /// </summary>
1876

    
1877
    public class XQueryCallFunction : Example
1878
    {
1879

    
1880
        public override string testName
1881
        {
1882
            get { return "XQueryCallFunction"; }
1883
        }
1884

    
1885
        public override void run(Uri samplesDir)
1886
        {
1887
            Processor processor = new Processor();
1888

    
1889
            XQueryCompiler qc = processor.NewXQueryCompiler();
1890
            XQueryExecutable exp1 = qc.Compile("declare namespace f='f.ns';" +
1891
                   "declare variable $z := 1 + xs:integer(doc-available('" + new Uri(samplesDir, "data/books.xml").ToString() + "'));" +
1892
                   "declare variable $p as xs:integer external;" +
1893
                   "declare function f:t1($v1 as xs:integer) { " +
1894
                   "   $v1 div $z + $p" +
1895
                   "};" +
1896
                   "10");
1897
            XQueryEvaluator ev = exp1.Load();
1898
            ev.SetExternalVariable(new QName("", "p"), new XdmAtomicValue(39));
1899
            XdmValue v1 = new XdmAtomicValue(10);
1900
            XdmValue result = ev.CallFunction(new QName("f.ns", "f:t1"), new XdmValue[] { v1 });
1901
            Console.WriteLine("First result (expected 44): " + result.ToString());
1902
            v1 = new XdmAtomicValue(20);
1903
            result = ev.CallFunction(new QName("f.ns", "f:t1"), new XdmValue[] { v1 });
1904
            Console.WriteLine("Second result (expected 49): " + result.ToString());
1905
        }
1906

    
1907
    }
1908

    
1909

    
1910
    /// <summary>
1911
    /// Show a query reading an input document using an XmlReader (the .NET XML parser)
1912
    /// </summary>
1913

    
1914
    public class XQueryFromXmlReader : Example
1915
    {
1916

    
1917
        public override string testName
1918
        {
1919
            get { return "XQueryFromXmlReader"; }
1920
        }
1921

    
1922
        public override void run(Uri samplesDir)
1923
        {
1924
            Processor processor = new Processor();
1925

    
1926
            String inputFileName = new Uri(samplesDir, "data/books.xml").ToString();
1927
            XmlTextReader reader = new XmlTextReader(inputFileName,
1928
                UriConnection.getReadableUriStream(new Uri(samplesDir, "data/books.xml")));
1929
            //new FileStream(inputFileName, FileMode.Open, FileAccess.Read));
1930
            reader.Normalization = true;
1931

    
1932
            // add a validating reader - not to perform validation, but to expand entity references
1933
            XmlValidatingReader validator = new XmlValidatingReader(reader);
1934
            validator.ValidationType = ValidationType.None;
1935

    
1936
            XdmNode doc = processor.NewDocumentBuilder().Build(validator);
1937

    
1938
            XQueryCompiler compiler = processor.NewXQueryCompiler();
1939
            XQueryExecutable exp = compiler.Compile("/");
1940
            XQueryEvaluator eval = exp.Load();
1941
            eval.ContextItem = doc;
1942
            Serializer qout = new Serializer();
1943
            qout.SetOutputProperty(Serializer.METHOD, "xml");
1944
            qout.SetOutputProperty(Serializer.INDENT, "yes");
1945
			qout.SetOutputStream(new FileStream("testoutput2.xml", FileMode.Create, FileAccess.Write));
1946
			Console.WriteLine("Output written to testoutput2.xml");
1947
            eval.Run(qout);
1948
        }
1949

    
1950
    }
1951

    
1952
    /// <summary>
1953
    /// Show a query producing a sequence as its result and returning the sequence
1954
    /// to the C# application in the form of an iterator. The sequence is then
1955
    /// output by serializing each item individually, with each item on a new line.
1956
    /// </summary>
1957

    
1958
    public class XQueryToSerializedSequence : Example
1959
    {
1960

    
1961
        public override string testName
1962
        {
1963
            get { return "XQueryToSerializedSequence"; }
1964
        }
1965

    
1966
        public override void run(Uri samplesDir)
1967
        {
1968
            Processor processor = new Processor();
1969
            String inputFileName = new Uri(samplesDir, "data/books.xml").ToString();
1970
            //XmlTextReader reader = new XmlTextReader(inputFileName,
1971
            //    new FileStream(inputFileName, FileMode.Open, FileAccess.Read));
1972
            XmlTextReader reader = new XmlTextReader(inputFileName,
1973
                UriConnection.getReadableUriStream(new Uri(samplesDir, "data/books.xml")));
1974
            reader.Normalization = true;
1975

    
1976
            // add a validating reader - not to perform validation, but to expand entity references
1977
            XmlValidatingReader validator = new XmlValidatingReader(reader);
1978
            validator.ValidationType = ValidationType.None;
1979

    
1980
            XdmNode doc = processor.NewDocumentBuilder().Build(reader);
1981

    
1982
            XQueryCompiler compiler = processor.NewXQueryCompiler();
1983
            XQueryExecutable exp = compiler.Compile("//ISBN");
1984
            XQueryEvaluator eval = exp.Load();
1985
            eval.ContextItem = doc;
1986

    
1987
            foreach (XdmNode node in eval)
1988
            {
1989
                Console.WriteLine(node.OuterXml);
1990
            }
1991
        }
1992

    
1993
    }
1994

    
1995
    /// <summary>
1996
    /// Show a query that takes a parameter (external variable) as input.
1997
    /// The query produces a single atomic value as its result and returns the value
1998
    /// to the C# application. 
1999
    /// </summary>
2000

    
2001
    public class XQueryUsingParameter : Example
2002
    {
2003

    
2004
        public override string testName
2005
        {
2006
            get { return "XQueryUsingParameter"; }
2007
        }
2008

    
2009
        public override void run(Uri samplesDir)
2010
        {
2011
            Processor processor = new Processor();
2012
            XQueryCompiler compiler = processor.NewXQueryCompiler();
2013
            compiler.DeclareNamespace("p", "http://saxon.sf.net/ns/p");
2014
            XQueryExecutable exp = compiler.Compile(
2015
                    "declare variable $p:in as xs:integer external; $p:in * $p:in");
2016
            XQueryEvaluator eval = exp.Load();
2017
            eval.SetExternalVariable(new QName("http://saxon.sf.net/ns/p", "p:in"), new XdmAtomicValue(12));
2018
            XdmAtomicValue result = (XdmAtomicValue)eval.EvaluateSingle();
2019
            Console.WriteLine("Result type: " + result.Value.GetType());
2020
            Console.WriteLine("Result value: " + (long)result.Value);
2021
        }
2022

    
2023
    }
2024

    
2025
    /// <summary>
2026
    /// Show a query consisting of two modules, using a QueryResolver to resolve
2027
    /// the "import module" declaration
2028
    /// </summary>
2029

    
2030
    public class XQueryMultiModule : Example
2031
    {
2032

    
2033
        public override string testName
2034
        {
2035
            get { return "XQueryMultiModule"; }
2036
        }
2037

    
2038
        public override void run(Uri samplesDir)
2039
        {
2040

    
2041
            String mod1 = "import module namespace m2 = 'http://www.example.com/module2';" +
2042
                          "m2:square(3)";
2043

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

    
2047
            Processor processor = new Processor();
2048
            XQueryCompiler compiler = processor.NewXQueryCompiler();
2049

    
2050
            InlineModuleResolver resolver = new InlineModuleResolver();
2051
            resolver.AddModule(new Uri("http://www.example.com/module2"), mod2);
2052
            compiler.QueryResolver = resolver;
2053
            XQueryExecutable exp = compiler.Compile(mod1);
2054
            XQueryEvaluator eval = exp.Load();
2055

    
2056
            XdmAtomicValue result = (XdmAtomicValue)eval.EvaluateSingle();
2057
            Console.WriteLine("Result type: " + result.Value.GetType());
2058
            Console.WriteLine("Result value: " + (long)result.Value);
2059
        }
2060

    
2061
        // A simple QueryResolver designed to show that the actual query
2062
        // text can come from anywhere: in this case, the resolver maintains
2063
        // a simple mapping of module URIs onto strings.
2064

    
2065
        public class InlineModuleResolver : IQueryResolver
2066
        {
2067

    
2068
            private Hashtable modules = new Hashtable();
2069

    
2070
            public void AddModule(Uri moduleName, String moduleText)
2071
            {
2072
                modules.Add(moduleName, moduleText);
2073
            }
2074

    
2075
            public Uri[] GetModules(String moduleUri, Uri baseUri, String[] locationHints)
2076
            {
2077
                Uri[] result = { new Uri(moduleUri) };
2078
                return result;
2079
            }
2080

    
2081
            public Object GetEntity(Uri absoluteUri)
2082
            {
2083
                return modules[absoluteUri];
2084
            }
2085
        }
2086

    
2087
    }
2088

    
2089

    
2090
    public class UriConnection
2091
    {
2092

    
2093
        // Get a stream for reading from a file:// URI
2094

    
2095
        public static Stream getReadableUriStream(Uri uri)
2096
        {
2097
            WebRequest request = (WebRequest)WebRequest.Create(uri);
2098
            return request.GetResponse().GetResponseStream();
2099
        }
2100

    
2101
        // Get a stream for writing to a file:// URI
2102

    
2103
        public static Stream getWritableUriStream(Uri uri)
2104
        {
2105
            FileWebRequest request = (FileWebRequest)WebRequest.CreateDefault(uri);
2106
            request.Method = "POST";
2107
            return request.GetRequestStream();
2108
        }
2109
    }
2110

    
2111
    ///
2112
    /// A sample XmlResolver. In the case of a URI ending with ".txt", it returns the
2113
    /// URI itself, wrapped as an XML document. In the case of the URI "empty.xslt", it returns an empty
2114
    /// stylesheet. In all other cases, it returns null, which has the effect of delegating
2115
    /// processing to the standard XmlResolver.
2116
    ///
2117

    
2118
    public class UserXmlResolver : XmlUrlResolver
2119
    {
2120

    
2121
        public String Message = null;
2122

    
2123
        public override object GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn)
2124
        {
2125
            if (Message != null)
2126
            {
2127
                Console.WriteLine(Message + absoluteUri + " (role=" + role + ")");
2128
            }
2129

    
2130
            if (absoluteUri.ToString().EndsWith(".txt"))
2131
            {
2132
                MemoryStream ms = new MemoryStream();
2133
                StreamWriter tw = new StreamWriter(ms);
2134
                tw.Write("<uri>");
2135
                tw.Write(absoluteUri);
2136
                tw.Write("</uri>");
2137
                tw.Flush();
2138
                return new MemoryStream(ms.GetBuffer(), 0, (int)ms.Length);
2139
            }
2140
            if (absoluteUri.ToString().EndsWith("empty.xslt"))
2141
            {
2142
                String ss = "<transform xmlns='http://www.w3.org/1999/XSL/Transform' version='2.0'/>";
2143
                MemoryStream ms = new MemoryStream();
2144
                StreamWriter tw = new StreamWriter(ms);
2145
                tw.Write(ss);
2146
                tw.Flush();
2147
                return new MemoryStream(ms.GetBuffer(), 0, (int)ms.Length);
2148
            }
2149
            else
2150
            {
2151
                return null;
2152
            }
2153
        }
2154
    }
2155

    
2156
    public class UserResultDocumentHandler : IResultDocumentHandler
2157
    {
2158

    
2159
        private Hashtable results;
2160

    
2161
        public UserResultDocumentHandler(Hashtable table)
2162
        {
2163
            this.results = table;
2164
        }
2165

    
2166
        public XmlDestination HandleResultDocument(string href, Uri baseUri)
2167
        {
2168
            DomDestination destination = new DomDestination();
2169
            results[href] = destination;
2170
            return destination;
2171
        }
2172

    
2173
    }
2174
}
2175

    
2176

    
2177
//
2178
// The contents of this file are subject to the Mozilla Public License Version 1.0 (the "License");
2179
// you may not use this file except in compliance with the License. You may obtain a copy of the
2180
// License at http://www.mozilla.org/MPL/
2181
//
2182
// Software distributed under the License is distributed on an "AS IS" basis,
2183
// WITHOUT WARRANTY OF ANY KIND, either express or implied.
2184
// See the License for the specific language governing rights and limitations under the License.
2185
//
2186
// The Original Code is: all this file.
2187
//
2188
// The Initial Developer of the Original Code is Michael H. Kay.
2189
//
2190
// Portions created by (your name) are Copyright (C) (your legal entity). All Rights Reserved.
2191
//
2192
// Contributor(s): none.
2193
//
2194

    
2195

    
2196

    
2197

    
(2-2/5)