Project

Profile

Help

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

he / latest9.4 / hen / csource / samples / ExamplesEE.cs @ c3c84ba2

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 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 XsltShowingLineNumbers(),
52
                new XsltMultipleOutput(),
53
                new XsltUsingResultHandler(),
54
                new XsltUsingIdFunction(),
55
                new XsltUsingRegisteredCollection(),
56
                new XsltUsingDirectoryCollection(),
57
                new XsltExtensibility(),
58
                new XsltIntegratedExtension(),
59
                new XQueryToStream(),
60
                new XQueryToAtomicValue(),
61
                new XQueryToSequence(),
62
                new XQueryToDom(),
63
                new XQueryToXdm(),
64
                new XQueryCallFunction(),
65
                new XQueryFromXmlReader(),
66
                new XQueryMultiModule(),
67
                new XQueryToSerializedSequence(),
68
                new XQueryUsingParameter(),
69
                new XQueryExtensibility(),
70
                new XQueryUpdate(),
71
                new Validate(),
72
                new XQueryTryCatch(),
73
                new XQuerySchemaAware(),
74
                new XPathSchemaAware(),
75
                new XsltStreamDoc()
76
            };
77

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

    
81
            String samplesPath = null;
82
            Uri samplesDir;
83

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

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

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

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

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

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

    
204
    ///<summary>
205
    /// Each of the example programs is implemented as a subclass of the abstract class Example
206
    ///</summary> 
207

    
208

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

    
221
    /// <summary>
222
    /// XPath expression selecting from a source document supplied as a URI
223
    /// </summary>
224

    
225
    public class XPathSimple : Example
226
    {
227

    
228
        public override String testName
229
        {
230
            get { return "XPathSimple"; }
231
        }
232

    
233
        /// <summary>
234
        /// Run a transformation: simplest possible script
235
        /// </summary>
236

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

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

    
245
            // Create an XPath compiler
246
            XPathCompiler xpath = processor.NewXPathCompiler();
247

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

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

    
260
    /// <summary>
261
    /// XPath expression using variables (and no source document)
262
    /// </summary>
263

    
264
    public class XPathVariables : Example
265
    {
266

    
267
        public override String testName
268
        {
269
            get { return "XPathVariables"; }
270
        }
271

    
272
        /// <summary>
273
        /// Run a transformation: simplest possible script
274
        /// </summary>
275

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

    
281
            // Create the XPath expression.
282
            XPathCompiler compiler = processor.NewXPathCompiler();
283
            compiler.DeclareVariable(new QName("", "a"));
284
            compiler.DeclareVariable(new QName("", "b"));
285
            XPathSelector selector = compiler.Compile("$a + $b").Load();
286

    
287
            // Set the values of the variables
288
            selector.SetVariable(new QName("", "a"), new XdmAtomicValue(2));
289
            selector.SetVariable(new QName("", "b"), new XdmAtomicValue(3));
290

    
291
            // Evaluate the XPath expression
292
            Console.WriteLine(selector.EvaluateSingle().ToString());
293
        }
294
    }
295

    
296
    /// <summary>
297
    /// XPath expression using variables without explicit declaration
298
    /// </summary>
299

    
300
    public class XPathUndeclaredVariables : Example
301
    {
302

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

    
308
        /// <summary>
309
        /// Execute an XPath expression containing undeclared variables
310
        /// </summary>
311

    
312
        public override void run(Uri samplesDir)
313
        {
314
            // Create a Processor instance.
315
            Processor processor = new Processor();
316

    
317
            // Create the XPath expression.
318
            XPathCompiler compiler = processor.NewXPathCompiler();
319
            compiler.AllowUndeclaredVariables = true;
320
            XPathExecutable expression = compiler.Compile("$a + $b");
321
            XPathSelector selector = expression.Load();
322

    
323
            // Set the values of the variables
324
            IEnumerator vars = expression.EnumerateExternalVariables();
325
            while (vars.MoveNext())
326
            {
327
                selector.SetVariable((QName)vars.Current, new XdmAtomicValue(10));
328
            }
329

    
330
            // Evaluate the XPath expression
331
            Console.WriteLine(selector.EvaluateSingle().ToString());
332
        }
333
    }
334

    
335
    /// <summary>
336
    /// XPath expression throwing a static error
337
    /// </summary>
338

    
339
    public class XPathWithStaticError : Example
340
    {
341

    
342
        public override String testName
343
        {
344
            get { return "XPathWithStaticError"; }
345
        }
346

    
347
        /// <summary>
348
        /// Execute an XPath expression that throws a dynamic error, and catch the error
349
        /// </summary>
350

    
351
        public override void run(Uri samplesDir)
352
        {
353
            // Create a Processor instance.
354
            Processor processor = new Processor();
355

    
356
            // Create the XPath expression.
357
            XPathCompiler compiler = processor.NewXPathCompiler();
358
            compiler.AllowUndeclaredVariables = true;
359
            XPathExecutable expression = compiler.Compile("1 + unknown()");
360
            XPathSelector selector = expression.Load();
361

    
362
            // Evaluate the XPath expression
363
            Console.WriteLine(selector.EvaluateSingle().ToString());
364
        }
365
    }
366

    
367
    /// <summary>
368
    /// XPath expression throwing a dynamic error
369
    /// </summary>
370

    
371
    public class XPathWithDynamicError : Example
372
    {
373

    
374
        public override String testName
375
        {
376
            get { return "XPathWithDynamicError"; }
377
        }
378

    
379
        /// <summary>
380
        /// Execute an XPath expression that throws a dynamic error
381
        /// </summary>
382

    
383
        public override void run(Uri samplesDir)
384
        {
385
            // Create a Processor instance.
386
            Processor processor = new Processor();
387

    
388
            // Create the XPath expression.
389
            XPathCompiler compiler = processor.NewXPathCompiler();
390
            compiler.AllowUndeclaredVariables = true;
391
            XPathExecutable expression = compiler.Compile("$a gt $b");
392
            XPathSelector selector = expression.Load();
393

    
394
            // Set the values of the variables
395
            selector.SetVariable(new QName("", "a"), new XdmAtomicValue(10));
396
            selector.SetVariable(new QName("", "b"), new XdmAtomicValue("Paris"));
397

    
398
            // Evaluate the XPath expression
399
            Console.WriteLine(selector.EvaluateSingle().ToString());
400
        }
401
    }
402

    
403
    /// <summary>
404
    /// XSLT 2.0 transformation with source document and stylesheet supplied as URIs
405
    /// </summary>
406

    
407
    public class XsltSimple1 : Example
408
    {
409

    
410
        public override String testName
411
        {
412
            get { return "XsltSimple1"; }
413
        }
414

    
415
        /// <summary>
416
        /// Run a transformation: simplest possible script
417
        /// </summary>
418

    
419
        public override void run(Uri samplesDir)
420
        {
421
            // Create a Processor instance.
422
            Processor processor = new Processor();
423

    
424
            // Load the source document
425
            XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/books.xml"));
426

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

    
430
            // Set the root node of the source document to be the initial context node
431
            transformer.InitialContextNode = input;
432

    
433
            // Create a serializer, with output to the standard output stream
434
            Serializer serializer = new Serializer();
435
            serializer.SetOutputWriter(Console.Out);
436

    
437
            // Transform the source XML and serialize the result document
438
            transformer.Run(serializer);
439
        }
440
    }
441

    
442
    /// <summary>
443
    /// Run a transformation, sending the serialized output to a file
444
    /// </summary>
445

    
446
    public class XsltSimple2 : Example
447
    {
448

    
449
        public override String testName
450
        {
451
            get { return "XsltSimple2"; }
452
        }
453

    
454
        /// <summary>
455
        /// Run the transformation, sending the serialized output to a file
456
        /// </summary>
457

    
458

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

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

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

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

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

    
478
            // Transform the source XML to System.out.
479
            transformer.Run(serializer);
480

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

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

    
489
    public class XsltSimple3 : Example
490
    {
491

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

    
497
        /// <summary>
498
        /// Run a transformation: supply input as a file
499
        /// </summary>
500

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

    
511
            // Create a Processor instance.
512
            Processor processor = new Processor();
513

    
514
            // Load the source document
515

    
516
            DocumentBuilder builder = processor.NewDocumentBuilder();
517
            builder.BaseUri = new Uri(samplesDir, "data/books.xml");
518

    
519
            XdmNode input = builder.Build(File.OpenRead(sourceFile));
520

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

    
526
            // Set the root node of the source document to be the initial context node
527
            transformer.InitialContextNode = input;
528

    
529
            // Create a serializer, with output to the standard output stream
530
            Serializer serializer = new Serializer();
531
            serializer.SetOutputWriter(Console.Out);
532

    
533
            // Transform the source XML and serialize the result document
534
            transformer.Run(serializer);
535
        }
536
    }
537

    
538

    
539
    /// <summary>
540
    /// XSLT 2.0 transformation showing stripping of whitespace controlled by the stylesheet
541
    /// </summary>
542

    
543
    public class XsltStripSpace : Example
544
    {
545

    
546
        public override String testName
547
        {
548
            get { return "XsltStripSpace"; }
549
        }
550

    
551
        /// <summary>
552
        /// Run a transformation: simplest possible script
553
        /// </summary>
554

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

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

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

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

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

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

    
587
            // Create a serializer
588
            Serializer serializer = new Serializer();
589
            serializer.SetOutputWriter(Console.Out);
590

    
591
            // Transform the source XML to System.out.
592
            transformer.Run(serializer);
593
        }
594
    }
595

    
596

    
597
    /// <summary>
598
    /// Run a transformation, compiling the stylesheet once and using it to transform two different source documents
599
    /// </summary>
600

    
601
    public class XsltReuseExecutable : Example
602
    {
603

    
604
        public override String testName
605
        {
606
            get { return "XsltReuseExecutable"; }
607
        }
608

    
609
        /// <summary>
610
        /// Show that a stylesheet can be compiled once (into an XsltExecutable) and run many times
611
        /// </summary>
612
        /// <param name="fileNames">
613
        /// 1. first source document
614
        /// 2. second source document
615
        /// 3. stylesheet used to transform both documents
616
        /// </param>
617

    
618
        public override void run(Uri samplesDir)
619
        {
620
            // Create a Processor instance.
621
            Processor processor = new Processor();
622

    
623
            // Create a compiled stylesheet
624
            XsltExecutable templates = processor.NewXsltCompiler().Compile(new Uri(samplesDir, "styles/summarize.xsl"));
625

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

    
629
            String sourceFile1 = "data/books.xml";
630
            String sourceFile2 = "data/othello.xml";
631

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

    
638
            // Do the second transformation
639
            Console.WriteLine("\n\n----- transform of " + sourceFile2 + " -----");
640
            XsltTransformer transformer2 = templates.Load();
641
            transformer2.InitialContextNode = processor.NewDocumentBuilder().Build(new Uri(samplesDir, sourceFile2));
642
            transformer2.Run(new Serializer());     // default destination is Console.Out    
643
        }
644
    }
645

    
646
    /// <summary>
647
    /// Show that the XsltTransformer is serially reusable; run a transformation twice using the same stylesheet
648
    /// and the same input document but with different parameters.
649
    /// </summary>
650

    
651
    public class XsltReuseTransformer : Example
652
    {
653

    
654
        public override String testName
655
        {
656
            get { return "XsltReuseTransformer"; }
657
        }
658

    
659
        /// <summary>
660
        /// Show that the XsltTransformer is serially reusable (we run it twice with different parameter settings)
661
        /// </summary>
662

    
663
        public override void run(Uri samplesDir)
664
        {
665
            // Create a Processor instance.
666
            Processor processor = new Processor();
667

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

    
671
            // Compile the stylesheet
672
            XsltExecutable exec = processor.NewXsltCompiler().Compile(new Uri(samplesDir, "styles/summarize.xsl"));
673

    
674
            // Create a transformer 
675
            XsltTransformer transformer = exec.Load();
676

    
677
            // Run it once        
678
            transformer.SetParameter(new QName("", "", "include-attributes"), new XdmAtomicValue(false));
679
            transformer.InitialContextNode = input;
680
            XdmDestination results = new XdmDestination();
681
            transformer.Run(results);
682
            Console.WriteLine("1: " + results.XdmNode.OuterXml);
683

    
684
            // Run it again        
685
            transformer.SetParameter(new QName("", "", "include-attributes"), new XdmAtomicValue(true));
686
            transformer.InitialContextNode = input;
687
            results.Reset();
688
            transformer.Run(results);
689
            Console.WriteLine("2: " + results.XdmNode.OuterXml);
690
        }
691
    }
692

    
693
    /// <summary>
694
    /// Run a sequence of transformations in a pipeline, each one acting as a filter
695
    /// </summary>
696

    
697
    public class XsltFilterChain : Example
698
    {
699

    
700
        public override String testName
701
        {
702
            get { return "XsltFilterChain"; }
703
        }
704

    
705
        /// <summary>
706
        /// Run the test
707
        /// </summary>
708

    
709
        public override void run(Uri samplesDir)
710
        {
711
            // Create a Processor instance.
712
            Processor processor = new Processor();
713

    
714
            // Load the source document
715
            XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/books.xml"));
716

    
717
            // Create a compiler
718
            XsltCompiler compiler = processor.NewXsltCompiler();
719

    
720
            // Compile all three stylesheets
721
            XsltTransformer transformer1 = compiler.Compile(new Uri(samplesDir, "styles/identity.xsl")).Load();
722
            XsltTransformer transformer2 = compiler.Compile(new Uri(samplesDir, "styles/books.xsl")).Load();
723
            XsltTransformer transformer3 = compiler.Compile(new Uri(samplesDir, "styles/summarize.xsl")).Load();
724

    
725
            // Now run them in series
726
            transformer1.InitialContextNode = input;
727
            XdmDestination results1 = new XdmDestination();
728
            transformer1.Run(results1);
729
            //Console.WriteLine("After phase 1:");
730
            //Console.WriteLine(results1.XdmNode.OuterXml);
731

    
732
            transformer2.InitialContextNode = results1.XdmNode;
733
            XdmDestination results2 = new XdmDestination();
734
            transformer2.Run(results2);
735
            //Console.WriteLine("After phase 2:");
736
            //Console.WriteLine(results2.XdmNode.OuterXml);
737

    
738
            transformer3.InitialContextNode = results2.XdmNode;
739
            //TextWriterDestination results3 = new TextWriterDestination(new XmlTextWriter(Console.Out));
740
            XdmDestination results3 = new XdmDestination();
741
            transformer3.Run(results3);
742
            Console.WriteLine("After phase 3:");
743
            Console.WriteLine(results3.XdmNode.OuterXml);
744
        }
745
    }
746

    
747
    /// <summary>
748
    /// Transform from an XDM tree to an XDM tree
749
    /// </summary>
750

    
751
    public class XsltXdmToXdm : Example
752
    {
753

    
754
        public override String testName
755
        {
756
            get { return "XsltXdmToXdm"; }
757
        }
758

    
759
        /// <summary>
760
        /// Transform from an XDM tree to an XDM tree
761
        /// </summary>
762

    
763
        public override void run(Uri samplesDir)
764
        {
765
            // Create a Processor instance.
766
            Processor processor = new Processor();
767

    
768
            // Load the source document
769
            XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/books.xml"));
770

    
771
            // Create a compiler
772
            XsltCompiler compiler = processor.NewXsltCompiler();
773

    
774
            // Compile the stylesheet
775
            XsltTransformer transformer = compiler.Compile(new Uri(samplesDir, "styles/summarize.xsl")).Load();
776

    
777
            // Run the transformation
778
            transformer.InitialContextNode = input;
779
            XdmDestination result = new XdmDestination();
780
            transformer.Run(result);
781

    
782
            // Serialize the result so we can see that it worked
783
            StringWriter sw = new StringWriter();
784
            result.XdmNode.WriteTo(new XmlTextWriter(sw));
785
            Console.WriteLine(sw.ToString());
786

    
787
            // Note: we don't do 
788
            //   result.XdmNode.WriteTo(new XmlTextWriter(Console.Out));
789
            // because that results in the Console.out stream being closed, 
790
            // with subsequent attempts to write to it being rejected.
791
        }
792
    }
793

    
794
    /// <summary>
795
    /// Run an XSLT transformation from an Xdm tree, starting at a node that is not the document node
796
    /// </summary>
797

    
798
    public class XsltXdmElementToXdm : Example
799
    {
800

    
801
        public override String testName
802
        {
803
            get { return "XsltXdmElementToXdm"; }
804
        }
805

    
806
        /// <summary>
807
        /// Run an XSLT transformation from an Xdm tree, starting at a node that is not the document node
808
        /// </summary>
809
        /// <param name="fileNames">
810
        /// 1. The source document
811
        /// 2. The stylesheet
812
        /// </param>
813

    
814
        public override void run(Uri samplesDir)
815
        {
816
            // Create a Processor instance.
817
            Processor processor = new Processor();
818

    
819
            // Load the source document
820
            XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/othello.xml"));
821

    
822
            // Navigate to the first grandchild
823
            XPathSelector eval = processor.NewXPathCompiler().Compile("/PLAY/FM[1]").Load();
824
            eval.ContextItem = input;
825
            input = (XdmNode)eval.EvaluateSingle();
826

    
827
            // Create an XSLT compiler
828
            XsltCompiler compiler = processor.NewXsltCompiler();
829

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

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

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

    
843
    /// <summary>
844
    /// Run a transformation from a DOM (System.Xml.Document) input to a DOM output
845
    /// </summary>
846

    
847
    public class XsltDomToDom : Example
848
    {
849

    
850
        public override String testName
851
        {
852
            get { return "XsltDomToDom"; }
853
        }
854

    
855
        /// <summary>
856
        /// Run a transformation from a DOM (System.Xml.Document) input to a DOM output
857
        /// </summary>
858

    
859
        public override void run(Uri samplesDir)
860
        {
861

    
862
            // Create a Processor instance.
863
            Processor processor = new Processor();
864

    
865
            // Load the source document (in practice, it would already exist as a DOM)
866
            XmlDocument doc = new XmlDocument();
867
            doc.Load(new XmlTextReader(samplesDir.AbsolutePath + "data/othello.xml"));
868
            XdmNode input = processor.NewDocumentBuilder().Wrap(doc);
869

    
870
            // Create a compiler
871
            XsltCompiler compiler = processor.NewXsltCompiler();
872

    
873
            // Compile the stylesheet
874
            XsltTransformer transformer = compiler.Compile(new Uri(samplesDir, "styles/summarize.xsl")).Load();
875

    
876
            // Run the transformation
877
            transformer.InitialContextNode = input;
878
            DomDestination result = new DomDestination();
879
            transformer.Run(result);
880

    
881
            // Serialize the result so we can see that it worked
882
            Console.WriteLine(result.XmlDocument.OuterXml);
883
        }
884
    }
885

    
886

    
887
    /// <summary>
888
    /// Run a transformation driven by an xml-stylesheet processing instruction in the source document
889
    /// </summary>
890

    
891
    public class XsltProcessingInstruction : Example
892
    {
893

    
894
        public override string testName
895
        {
896
            get { return "XsltProcessingInstruction"; }
897
        }
898

    
899
        /// <summary>
900
        /// Run a transformation driven by an xml-stylesheet processing instruction in the source document
901
        /// </summary>
902
        /// <param name="fileNames">
903
        /// 1. The source document
904
        /// </param>
905

    
906
        public override void run(Uri samplesDir)
907
        {
908
            // Create a Processor instance.
909
            Processor processor = new Processor();
910
            XsltExecutable exec;
911

    
912
            // Load the source document
913
            XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/books.xml"));
914
            //Console.WriteLine("=============== source document ===============");
915
            //Console.WriteLine(input.OuterXml);
916
            //Console.WriteLine("=========== end of source document ============");
917

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

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

    
924
            XPathSelector eval = processor.NewXPathCompiler().Compile(path).Load();
925
            eval.ContextItem = input;
926
            XdmAtomicValue hrefval = (XdmAtomicValue)eval.EvaluateSingle();
927
            String href = (hrefval == null ? null : hrefval.ToString());
928

    
929
            if (href == null || href == "")
930
            {
931
                Console.WriteLine("No suitable xml-stylesheet processing instruction found");
932
                return;
933

    
934
            }
935
            else if (href[0] == '#')
936
            {
937

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

    
940
                Console.WriteLine("Locating embedded stylesheet with href = " + href);
941
                String idpath = "id('" + href.Substring(1) + "')";
942
                eval = processor.NewXPathCompiler().Compile(idpath).Load();
943
                eval.ContextItem = input;
944
                XdmNode node = (XdmNode)eval.EvaluateSingle();
945
                if (node == null)
946
                {
947
                    Console.WriteLine("No element found with ID " + href.Substring(1));
948
                    return;
949
                }
950
                exec = processor.NewXsltCompiler().Compile(node);
951

    
952
            }
953
            else
954
            {
955

    
956
                // The stylesheet is in an external document
957

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

    
960
                // Fetch and compile the referenced stylesheet
961
                exec = processor.NewXsltCompiler().Compile(new Uri(input.BaseUri, href.ToString()));
962
            }
963

    
964
            // Create a transformer 
965
            XsltTransformer transformer = exec.Load();
966

    
967
            // Run it       
968
            transformer.InitialContextNode = input;
969
            XdmDestination results = new XdmDestination();
970
            transformer.Run(results);
971
            Console.WriteLine("1: " + results.XdmNode.OuterXml);
972

    
973
        }
974
    }
975

    
976
    /// <summary>
977
    /// Run an XSLT transformation setting serialization properties from the calling application
978
    /// </summary>
979

    
980
    public class XsltSettingOutputProperties : Example
981
    {
982

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

    
988
        /// <summary>
989
        /// Run an XSLT transformation setting serialization properties from the calling application
990
        /// </summary>
991

    
992
        public override void run(Uri samplesDir)
993
        {
994
            // Create a Processor instance.
995
            Processor processor = new Processor();
996

    
997
            // Load the source document
998
            XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/books.xml"));
999

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

    
1003
            // Set the root node of the source document to be the initial context node
1004
            transformer.InitialContextNode = input;
1005

    
1006
            // Create a serializer, with output to the standard output stream
1007
            Serializer serializer = new Serializer();
1008
            serializer.SetOutputProperty(Serializer.METHOD, "xml");
1009
            serializer.SetOutputProperty(Serializer.INDENT, "no");
1010
            serializer.SetOutputWriter(Console.Out);
1011

    
1012
            // Transform the source XML and serialize the result document
1013
            transformer.Run(serializer);
1014
        }
1015

    
1016
    }
1017

    
1018
    /// <summary>
1019
    /// Run an XSLT transformation making use of an XmlResolver to resolve URIs at document build time, at stylesheet compile time 
1020
    /// and at transformation run-time
1021
    /// </summary>
1022

    
1023
    public class XsltUsingSourceResolver : Example
1024
    {
1025

    
1026
        public override string testName
1027
        {
1028
            get { return "XsltUsingSourceResolver"; }
1029
        }
1030

    
1031
        /// <summary>
1032
        /// Run an XSLT transformation making use of an XmlResolver to resolve URIs both at compile time and at run-time
1033
        /// </summary>
1034

    
1035
        public override void run(Uri samplesDir)
1036
        {
1037

    
1038
            // Create a Processor instance.
1039
            Processor processor = new Processor();
1040

    
1041
            // Load the source document
1042
            DocumentBuilder builder = processor.NewDocumentBuilder();
1043
            UserXmlResolver buildTimeResolver = new UserXmlResolver();
1044
            buildTimeResolver.Message = "** Calling build-time XmlResolver: ";
1045
            builder.XmlResolver = buildTimeResolver;
1046
            builder.BaseUri = samplesDir;
1047

    
1048
            String doc = "<!DOCTYPE doc [<!ENTITY e SYSTEM 'flamingo.txt'>]><doc>&e;</doc>";
1049
            MemoryStream ms = new MemoryStream();
1050
            StreamWriter tw = new StreamWriter(ms);
1051
            tw.Write(doc);
1052
            tw.Flush();
1053
            Stream instr = new MemoryStream(ms.GetBuffer(), 0, (int)ms.Length);
1054
            XdmNode input = builder.Build(instr);
1055

    
1056
            // Create a transformer for the stylesheet.
1057
            String stylesheet =
1058
                "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0'>" +
1059
                "<xsl:import href='empty.xslt'/>" +
1060
                "<xsl:template match='/'>" +
1061
                "<out note=\"{doc('heron.txt')}\" ><xsl:copy-of select='.'/></out>" +
1062
                "</xsl:template>" +
1063
                "</xsl:stylesheet>";
1064

    
1065
            XsltCompiler compiler = processor.NewXsltCompiler();
1066
            UserXmlResolver compileTimeResolver = new UserXmlResolver();
1067
            compileTimeResolver.Message = "** Calling compile-time XmlResolver: ";
1068
            compiler.XmlResolver = compileTimeResolver;
1069
            compiler.BaseUri = samplesDir;
1070
            XsltTransformer transformer = compiler.Compile(new XmlTextReader(new StringReader(stylesheet))).Load();
1071

    
1072
            // Set the root node of the source document to be the initial context node
1073
            transformer.InitialContextNode = input;
1074

    
1075
            // Set the user-written XmlResolver
1076
            UserXmlResolver runTimeResolver = new UserXmlResolver();
1077
            runTimeResolver.Message = "** Calling transformation-time XmlResolver: ";
1078
            transformer.InputXmlResolver = runTimeResolver;
1079

    
1080
            // Create a serializer
1081
            Serializer serializer = new Serializer();
1082
            serializer.SetOutputWriter(Console.Out);
1083

    
1084
            // Transform the source XML to System.out.
1085
            transformer.Run(serializer);
1086

    
1087
        }
1088
    }
1089

    
1090
    /// <summary>
1091
    /// Run an XSLT transformation displaying compile-time errors to the console
1092
    /// </summary>
1093

    
1094
    public class XsltDisplayingErrors : Example
1095
    {
1096

    
1097
        public override string testName
1098
        {
1099
            get { return "XsltDisplayingErrors"; }
1100
        }
1101

    
1102
        /// <summary>
1103
        /// Run an XSLT transformation displaying compile-time errors to the console
1104
        /// </summary>
1105

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

    
1111
            // Create the XSLT Compiler
1112
            XsltCompiler compiler = processor.NewXsltCompiler();
1113

    
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='eee: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 XmlTextReader(new StringReader(stylesheet)));
1132
                Console.WriteLine("Stylesheet compilation succeeded");
1133
            }
1134
            catch (Exception)
1135
            {
1136
                Console.WriteLine("Stylesheet compilation failed");
1137
            }
1138

    
1139

    
1140
        }
1141
    }
1142

    
1143
    /// <summary>
1144
    /// Run an XSLT transformation capturing compile-time errors within the application
1145
    /// </summary>
1146

    
1147
    public class XsltCapturingErrors : Example
1148
    {
1149

    
1150
        public override string testName
1151
        {
1152
            get { return "XsltCapturingErrors"; }
1153
        }
1154

    
1155
        /// <summary>
1156
        /// Run an XSLT transformation capturing compile-time errors within the application
1157
        /// </summary>
1158

    
1159
        public override void run(Uri samplesDir)
1160
        {
1161
            // Create a Processor instance.
1162
            Processor processor = new Processor();
1163

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

    
1167
            // Create a list to hold the error information
1168
            compiler.ErrorList = new ArrayList();
1169

    
1170
            // Define a stylesheet containing errors
1171
            String stylesheet =
1172
                "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0'>\n" +
1173
                "<xsl:template name='fff:template'>\n" +
1174
                "  <xsl:value-of select='32'/>\n" +
1175
                "</xsl:template>\n" +
1176
                "<xsl:template name='main'>\n" +
1177
                "  <xsl:value-of select='$var'/>\n" +
1178
                "</xsl:template>\n" +
1179
                "</xsl:stylesheet>";
1180

    
1181

    
1182
            // Attempt to compile the stylesheet and display the errors
1183
            try
1184
            {
1185
                compiler.BaseUri = new Uri("http://localhost/stylesheet");
1186
                compiler.Compile(new StringReader(stylesheet));
1187
                Console.WriteLine("Stylesheet compilation succeeded");
1188
            }
1189
            catch (Exception)
1190
            {
1191
                Console.WriteLine("Stylesheet compilation failed with " + compiler.ErrorList.Count + " errors");
1192
                foreach (StaticError error in compiler.ErrorList)
1193
                {
1194
                    Console.WriteLine("At line " + error.LineNumber + ": " + error.Message);
1195
                }
1196
            }
1197
        }
1198
    }
1199

    
1200
    /// <summary>
1201
    /// Run an XSLT transformation capturing run-time messages within the application
1202
    /// </summary>
1203

    
1204
    public class XsltCapturingMessages : Example
1205
    {
1206

    
1207
        public override string testName
1208
        {
1209
            get { return "XsltCapturingMessages"; }
1210
        }
1211

    
1212
        /// <summary>
1213
        /// Run an XSLT transformation capturing run-time messages within the application
1214
        /// </summary>
1215

    
1216
        public override void run(Uri samplesDir)
1217
        {
1218

    
1219
            // Create a Processor instance.
1220
            Processor processor = new Processor();
1221

    
1222
            // Create the XSLT Compiler
1223
            XsltCompiler compiler = processor.NewXsltCompiler();
1224

    
1225
            // Define a stylesheet that generates messages
1226
            String stylesheet =
1227
                "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0'>\n" +
1228
                "<xsl:template name='main'>\n" +
1229
                "  <xsl:message><a>starting</a></xsl:message>\n" +
1230
                "  <out><xsl:value-of select='current-date()'/></out>\n" +
1231
                "  <xsl:message><a>finishing</a></xsl:message>\n" +
1232
                "</xsl:template>\n" +
1233
                "</xsl:stylesheet>";
1234

    
1235
            compiler.BaseUri = new Uri("http://localhost/stylesheet");
1236
            XsltExecutable exec = compiler.Compile(new StringReader(stylesheet));
1237

    
1238

    
1239
            // Create a transformer for the stylesheet.
1240
            XsltTransformer transformer = exec.Load();
1241

    
1242
            // Set the name of the initial template
1243
            transformer.InitialTemplate = new QName("", "main");
1244

    
1245
            // Create a Listener to which messages will be written
1246
            transformer.MessageListener = new UserMessageListener();
1247

    
1248
            // Create a serializer
1249
            Serializer serializer = new Serializer();
1250
            serializer.SetOutputWriter(Console.Out);
1251

    
1252
            // Transform the source XML to System.out.
1253
            transformer.Run(serializer);
1254
        }
1255

    
1256
    }
1257

    
1258
    ///
1259
    /// Example user-written message listener
1260
    ///
1261

    
1262
    public class UserMessageListener : IMessageListener
1263
    {
1264

    
1265
        public void Message(XdmNode content, bool terminate, IXmlLocation location)
1266
        {
1267
            Console.Out.WriteLine("MESSAGE terminate=" + (terminate ? "yes" : "no") + " at " + DateTime.Now);
1268
            Console.Out.WriteLine("From instruction at line " + location.LineNumber +
1269
                    " of " + location.BaseUri);
1270
            Console.Out.WriteLine(">>" + content.StringValue);
1271
        }
1272
    }
1273

    
1274
    /// <summary>
1275
    /// Run an XSLT transformation showing source line numbers
1276
    /// </summary>
1277

    
1278
    public class XsltShowingLineNumbers : Example
1279
    {
1280

    
1281
        public override string testName
1282
        {
1283
            get { return "XsltShowingLineNumbers"; }
1284
        }
1285

    
1286
        /// <summary>
1287
        /// Run an XSLT transformation capturing run-time messages within the application
1288
        /// </summary>
1289

    
1290
        public override void run(Uri samplesDir)
1291
        {
1292

    
1293
            // Create a Processor instance.
1294
            Processor processor = new Processor();
1295

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

    
1299
            // Load the source document
1300
            DocumentBuilder builder = processor.NewDocumentBuilder();
1301
            builder.IsLineNumbering = true;
1302
            XdmNode input = builder.Build(new Uri(samplesDir, "data/othello.xml"));
1303

    
1304
            // Create the XSLT Compiler
1305
            XsltCompiler compiler = processor.NewXsltCompiler();
1306

    
1307
            // Define a stylesheet that shows line numbers of source elements
1308
            String stylesheet =
1309
                "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0' xmlns:saxon='http://saxon.sf.net/'>\n" +
1310
                "<xsl:template match='/'>\n" +
1311
                "<out>\n" +
1312
                "  <xsl:for-each select='//ACT'>\n" +
1313
                "  <out><xsl:value-of select='saxon:line-number(.)'/></out>\n" +
1314
                "  </xsl:for-each>\n" +
1315
                "</out>\n" +
1316
                "</xsl:template>\n" +
1317
                "</xsl:stylesheet>";
1318

    
1319
            compiler.BaseUri = new Uri("http://localhost/stylesheet");
1320
            XsltExecutable exec = compiler.Compile(new StringReader(stylesheet));
1321

    
1322

    
1323
            // Create a transformer for the stylesheet.
1324
            XsltTransformer transformer = exec.Load();
1325

    
1326
            // Set the root node of the source document to be the initial context node
1327
            transformer.InitialContextNode = input;
1328

    
1329
            // Create a serializer
1330
            Serializer serializer = new Serializer();
1331
            serializer.SetOutputWriter(Console.Out);
1332

    
1333
            // Transform the source XML to System.out.
1334
            transformer.Run(serializer);
1335
        }
1336

    
1337
    }
1338

    
1339
    /// <summary>
1340
    /// Run an XSLT transformation producing multiple output documents
1341
    /// </summary>
1342

    
1343
    public class XsltMultipleOutput : Example
1344
    {
1345

    
1346
        public override string testName
1347
        {
1348
            get { return "XsltMultipleOutput"; }
1349
        }
1350

    
1351
        /// <summary>
1352
        /// Run an XSLT transformation producing multiple output documents
1353
        /// </summary>
1354

    
1355
        public override void run(Uri samplesDir)
1356
        {
1357
            // Create a Processor instance.
1358
            Processor processor = new Processor();
1359
            processor.SetProperty("http://saxon.sf.net/feature/timing", "true");
1360

    
1361
            // Load the source document
1362
            XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/othello.xml"));
1363

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

    
1367
            // Set the root node of the source document to be the initial context node
1368
            transformer.InitialContextNode = input;
1369

    
1370
            // Set the required stylesheet parameter
1371
            transformer.SetParameter(new QName("", "", "dir"), new XdmAtomicValue(samplesDir.ToString() + "play"));
1372

    
1373
            // Create a serializer
1374
            Serializer serializer = new Serializer();
1375
            serializer.SetOutputWriter(Console.Out);
1376

    
1377
            // Transform the source XML to System.out.
1378
            transformer.Run(serializer);
1379

    
1380
        }
1381

    
1382
    }
1383

    
1384

    
1385
    /// <summary>
1386
    /// Run an XSLT transformation using the id() function, with DTD validation
1387
    /// </summary>
1388

    
1389
    public class XsltUsingIdFunction : Example
1390
    {
1391

    
1392
        public override string testName
1393
        {
1394
            get { return "XsltUsingIdFunction"; }
1395
        }
1396

    
1397
        /// <summary>
1398
        /// Run an XSLT transformation using the id() function, with DTD validation
1399
        /// </summary>
1400

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

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

    
1410
            String doc = "<!DOCTYPE table [" +
1411
                "<!ELEMENT table (row*)>" +
1412
                "<!ELEMENT row EMPTY>" +
1413
                "<!ATTLIST row xml:id ID #REQUIRED>" +
1414
                "<!ATTLIST row value CDATA #REQUIRED>]>" +
1415
                "<table><row xml:id='A123' value='green'/><row xml:id='Z789' value='blue'/></table>";
1416

    
1417
            DocumentBuilder builder = processor.NewDocumentBuilder();
1418
            builder.DtdValidation = true;
1419
            builder.BaseUri = samplesDir;
1420
            MemoryStream ms = new MemoryStream();
1421
            StreamWriter tw = new StreamWriter(ms);
1422
            tw.Write(doc);
1423
            tw.Flush();
1424
            Stream instr = new MemoryStream(ms.GetBuffer(), 0, (int)ms.Length);
1425
            XdmNode input = builder.Build(instr);
1426

    
1427
            // Define a stylesheet that uses the id() function
1428
            String stylesheet =
1429
                "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0'>\n" +
1430
                "<xsl:template match='/'>\n" +
1431
                "  <xsl:copy-of select=\"id('Z789')\"/>\n" +
1432
                "</xsl:template>\n" +
1433
                "</xsl:stylesheet>";
1434

    
1435
            XsltCompiler compiler = processor.NewXsltCompiler();
1436
            compiler.BaseUri = new Uri("http://localhost/stylesheet");
1437
            XsltExecutable exec = compiler.Compile(new StringReader(stylesheet));
1438

    
1439
            //Create a transformer for the stylesheet
1440
            XsltTransformer transformer = exec.Load();
1441

    
1442
            // Set the root node of the source document to be the initial context node
1443
            transformer.InitialContextNode = input;
1444

    
1445
            //Set the destination
1446
            XdmDestination results = new XdmDestination();
1447

    
1448
            // Transform the XML
1449
            transformer.Run(results);
1450

    
1451
            // Show the result
1452
            Console.WriteLine(results.XdmNode.ToString());
1453

    
1454
        }
1455

    
1456
    }
1457

    
1458
    /// <summary>
1459
    /// Show a transformation using a user-written result document handler. This example
1460
    /// captures each of the result documents in a DOM, and creates a Hashtable that indexes
1461
    /// the DOM trees according to their absolute URI. On completion, it writes all the DOMs
1462
    /// to the standard output.
1463
    /// </summary>
1464

    
1465
    public class XsltUsingResultHandler : Example
1466
    {
1467

    
1468
        public override string testName
1469
        {
1470
            get { return "XsltUsingResultHandler"; }
1471
        }
1472

    
1473
        /// <summary>
1474
        /// Show a transformation using a user-written result document handler. This example
1475
        /// captures each of the result documents in a DOM, and creates a Hashtable that indexes
1476
        /// the DOM trees according to their absolute URI. On completion, it writes all the DOMs
1477
        /// to the standard output.
1478
        /// </summary>
1479

    
1480
        public override void run(Uri samplesDir)
1481
        {
1482
            // Create a Processor instance.
1483
            Processor processor = new Processor();
1484

    
1485
            // Load the source document
1486
            XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/othello.xml"));
1487

    
1488
            // Define a stylesheet that splits the document up
1489
            String stylesheet =
1490
                "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0'>\n" +
1491
                "<xsl:template match='/'>\n" +
1492
                "  <xsl:for-each select='//ACT'>\n" +
1493
                "    <xsl:result-document href='{position()}.xml'>\n" +
1494
                "      <xsl:copy-of select='TITLE'/>\n" +
1495
                "    </xsl:result-document>\n" +
1496
                "  </xsl:for-each>\n" +
1497
                "</xsl:template>\n" +
1498
                "</xsl:stylesheet>";
1499

    
1500
            XsltCompiler compiler = processor.NewXsltCompiler();
1501
            compiler.BaseUri = new Uri("http://localhost/stylesheet");
1502
            XsltExecutable exec = compiler.Compile(new StringReader(stylesheet));
1503

    
1504
            // Create a transformer for the stylesheet.
1505
            XsltTransformer transformer = exec.Load();
1506

    
1507
            // Set the root node of the source document to be the initial context node
1508
            transformer.InitialContextNode = input;
1509

    
1510
            // Establish the result document handler
1511
            Hashtable results = new Hashtable();
1512
            transformer.ResultDocumentHandler = new UserResultDocumentHandler(results);
1513

    
1514
            // Transform the source XML to a NullDestination (because we only want the secondary result files).
1515
            transformer.Run(new NullDestination());
1516

    
1517
            // Process the captured DOM results
1518
            foreach (DictionaryEntry entry in results)
1519
            {
1520
                string uri = (string)entry.Key;
1521
                Console.WriteLine("\nResult File " + uri);
1522
                DomDestination dom = (DomDestination)results[uri];
1523
                Console.Write(dom.XmlDocument.OuterXml);
1524
            }
1525

    
1526
        }
1527

    
1528
    }
1529

    
1530
    /// <summary>
1531
    /// Show a transformation using a registered collection
1532
    /// </summary>
1533

    
1534
    public class XsltUsingRegisteredCollection : Example
1535
    {
1536

    
1537
        public override string testName
1538
        {
1539
            get { return "XsltUsingRegisteredCollection"; }
1540
        }
1541

    
1542
        /// <summary>
1543
        /// Show a transformation using a registered collection
1544
        /// </summary>
1545

    
1546
        public override void run(Uri samplesDir)
1547
        {
1548
            // Create a Processor instance.
1549
            Processor processor = new Processor();
1550

    
1551
            // Load the source document
1552
            XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/othello.xml"));
1553

    
1554
            // Define a stylesheet that splits the document up
1555
            String stylesheet =
1556
                "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0'>\n" +
1557
                "<xsl:template name='main'>\n" +
1558
                " <out>\n" +
1559
                "  <xsl:for-each select=\"collection('http://www.example.org/my-collection')\">\n" +
1560
                "    <document uri='{document-uri(.)}' nodes='{count(//*)}'/>\n" +
1561
                "  </xsl:for-each><zzz/>\n" +
1562
                "  <xsl:for-each select=\"collection('http://www.example.org/my-collection')\">\n" +
1563
                "    <document uri='{document-uri(.)}' nodes='{count(//*)}'/>\n" +
1564
                "  </xsl:for-each>\n" +
1565
                " </out>\n" +
1566
                "</xsl:template>\n" +
1567
                "</xsl:stylesheet>";
1568

    
1569
            Uri[] documentList = new Uri[2];
1570
            documentList[0] = new Uri(samplesDir, "data/othello.xml");
1571
            documentList[1] = new Uri(samplesDir, "data/books.xml");
1572
            processor.RegisterCollection(new Uri("http://www.example.org/my-collection"), documentList);
1573

    
1574
            XsltCompiler compiler = processor.NewXsltCompiler();
1575
            compiler.BaseUri = new Uri("http://localhost/stylesheet");
1576
            XsltExecutable exec = compiler.Compile(new StringReader(stylesheet));
1577

    
1578
            // Create a transformer for the stylesheet.
1579
            XsltTransformer transformer = exec.Load();
1580

    
1581
            // Set the root node of the source document to be the initial context node
1582
            transformer.InitialTemplate = new QName("", "main");
1583

    
1584
            //Set the destination
1585
            XdmDestination results = new XdmDestination();
1586

    
1587
            // Transform the XML
1588
            transformer.Run(results);
1589

    
1590
            // Show the result
1591
            Console.WriteLine(results.XdmNode.ToString());
1592

    
1593
        }
1594
    }
1595

    
1596
    /// <summary>
1597
    /// Show a transformation using a registered collection
1598
    /// </summary>
1599

    
1600
    public class XsltUsingDirectoryCollection : Example
1601
    {
1602

    
1603
        public override string testName
1604
        {
1605
            get { return "XsltUsingDirectoryCollection"; }
1606
        }
1607

    
1608
        /// <summary>
1609
        /// Show a transformation using a collection that maps to a directory
1610
        /// </summary>
1611

    
1612
        public override void run(Uri samplesDir)
1613
        {
1614
            // Create a Processor instance.
1615
            Processor processor = new Processor();
1616

    
1617
            // Load the source document
1618
            XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/othello.xml"));
1619

    
1620
            // Define a stylesheet that splits the document up
1621
            String stylesheet =
1622
                "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0'>\n" +
1623
                "<xsl:template name='main'>\n" +
1624
                " <out>\n" +
1625
                "  <xsl:for-each select=\"collection('" + samplesDir + "?recurse=yes;select=*.xml;on-error=warning')\">\n" +
1626
                "    <document uri='{document-uri(.)}' nodes='{count(//*)}'/>\n" +
1627
                "  </xsl:for-each><zzz/>\n" +
1628
                " </out>\n" +
1629
                "</xsl:template>\n" +
1630
                "</xsl:stylesheet>";
1631

    
1632

    
1633
            XsltCompiler compiler = processor.NewXsltCompiler();
1634
            compiler.BaseUri = new Uri("http://localhost/stylesheet");
1635
            XsltExecutable exec = compiler.Compile(new StringReader(stylesheet));
1636

    
1637
            // Create a transformer for the stylesheet.
1638
            XsltTransformer transformer = exec.Load();
1639

    
1640
            // Set the root node of the source document to be the initial context node
1641
            transformer.InitialTemplate = new QName("", "main");
1642

    
1643
            //Set the destination
1644
            XdmDestination results = new XdmDestination();
1645

    
1646
            // Transform the XML
1647
            transformer.Run(results);
1648

    
1649
            // Show the result
1650
            Console.WriteLine(results.XdmNode.ToString());
1651

    
1652
        }
1653

    
1654
    }
1655

    
1656
    /// <summary>
1657
    /// Show a transformation using calls to extension functions
1658
    /// </summary>
1659

    
1660
    public class XsltExtensibility : Example
1661
    {
1662

    
1663
        public override string testName
1664
        {
1665
            get { return "XsltExtensibility"; }
1666
        }
1667
        /// <summary>
1668
        /// Demonstrate XSLT extensibility using user-written extension functions
1669
        /// </summary>
1670
        /// <remarks>Note: If SamplesExtensions is compiled to a different assembly than ExamplesEE, use 
1671
        /// the namespace URI clitype:SampleExtensions.SampleExtensions?asm=ASSEMBLY_NAME_HERE
1672
        /// </remarks>
1673

    
1674
        public override void run(Uri samplesDir)
1675
        {
1676

    
1677
            // Create a Processor instance.
1678
            Processor processor = new Processor();
1679

    
1680
            // Identify the Processor version
1681
            Console.WriteLine(processor.ProductVersion);
1682

    
1683
            // Set diagnostics
1684
            //processor.SetProperty("http://saxon.sf.net/feature/trace-external-functions", "true");
1685

    
1686
            // Create the stylesheet
1687
            String s = @"<xsl:transform version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'" +
1688
                @" xmlns:ext='clitype:SampleExtensions.SampleExtensions?asm=ExamplesEE' " +
1689
                @" xmlns:tz='clitype:System.TimeZone' " +
1690
                @" xmlns:math='http://example.math.co.uk/demo' " +
1691
                @" xmlns:env='http://example.env.co.uk/demo' " +
1692
                @" exclude-result-prefixes='ext math env tz'> " +
1693
                @" <xsl:param name='timezone' required='yes'/> " +
1694
                @" <xsl:template match='/'> " +
1695
                @" <out addition='{ext:add(2,2)}' " +
1696
                @" average='{ext:average((1,2,3,4,5,6))}' " +
1697
                @" firstchild='{ext:nameOfFirstChild(.)}' " +
1698
                @" timezone='{tz:StandardName($timezone)}' " +
1699
                @" sqrt2='{math:sqrt(2.0e0)}' " +
1700
                @" defaultNamespace='{env:defaultNamespace()}' " +
1701
                @" sqrtEmpty='{math:sqrt(())}'> " +
1702
                @" <xsl:copy-of select='ext:FirstChild((//ITEM)[1])'/> " +
1703
                @" <defaultNS value='{env:defaultNamespace()}' xsl:xpath-default-namespace='http://default.namespace.com/' /> " +
1704
                @" <combine1><xsl:sequence select='ext:combine(ext:FirstChild((//ITEM)[1]), count(*))'/></combine1> " +
1705
                @" <combine2><xsl:sequence select='ext:combine((//TITLE)[1], (//AUTHOR)[1])'/></combine2> " +
1706
                @" </out> " +
1707
                @" </xsl:template></xsl:transform>";
1708

    
1709
            // Register the integrated extension functions math:sqrt and env:defaultNamespace
1710

    
1711
            processor.RegisterExtensionFunction(new Sqrt());
1712
            processor.RegisterExtensionFunction(new DefaultNamespace());
1713

    
1714
            // Create a transformer for the stylesheet.
1715
            XsltTransformer transformer = processor.NewXsltCompiler().Compile(new StringReader(s)).Load();
1716

    
1717
            // Load the source document (must be a wrapper around an XmlDocument for this test)
1718
            XmlDocument doc = new XmlDocument();
1719
            doc.Load(new XmlTextReader(samplesDir.AbsolutePath + "data/books.xml"));
1720
            XdmNode input = processor.NewDocumentBuilder().Wrap(doc);
1721

    
1722
            // Set the root node of the source document to be the initial context node
1723
            transformer.InitialContextNode = input;
1724

    
1725
            // Supply a parameter
1726
            transformer.SetParameter(new QName("", "timezone"),
1727
                      XdmAtomicValue.WrapExternalObject(TimeZone.CurrentTimeZone));
1728

    
1729
            // Create a serializer
1730
            Serializer serializer = new Serializer();
1731
            serializer.SetOutputWriter(Console.Out);
1732
            serializer.SetOutputProperty(Serializer.INDENT, "yes");
1733

    
1734
            // Transform the source XML to System.out.
1735
            transformer.Run(serializer);
1736
        }
1737

    
1738
    }
1739

    
1740
    /// <summary>
1741
    /// Show a transformation using calls to extension functions
1742
    /// </summary>
1743

    
1744
    public class XsltIntegratedExtension : Example
1745
    {
1746

    
1747
        public override string testName
1748
        {
1749
            get { return "XsltIntegratedExtension"; }
1750
        }
1751

    
1752
        /// <summary>
1753
        /// Show a transformation using calls to extension functions
1754
        /// </summary>
1755

    
1756
        public override void run(Uri samplesDir)
1757
        {
1758

    
1759
            // Create a Processor instance.
1760
            Processor processor = new Processor();
1761

    
1762
            // Identify the Processor version
1763
            Console.WriteLine(processor.ProductVersion);
1764

    
1765
            // Set diagnostics
1766
            //processor.SetProperty("http://saxon.sf.net/feature/trace-external-functions", "true");
1767

    
1768
            // Create the stylesheet
1769
            String s = @"<xsl:transform version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'" +
1770
                @" xmlns:math='http://example.math.co.uk/demo'> " +
1771
                @" <xsl:template name='go'> " +
1772
                @" <out sqrt2='{math:sqrt(2.0e0)}' " +
1773
                @" sqrtEmpty='{math:sqrt(())}'/> " +
1774
                @" </xsl:template></xsl:transform>";
1775

    
1776
            // Register the integrated extension function math:sqrt
1777

    
1778
            processor.RegisterExtensionFunction(new Sqrt());
1779

    
1780
            // Create a transformer for the stylesheet.
1781
            XsltTransformer transformer = processor.NewXsltCompiler().Compile(new StringReader(s)).Load();
1782

    
1783
            // Set the root node of the source document to be the initial context node
1784
            transformer.InitialTemplate = new QName("go");
1785

    
1786
            // Create a serializer
1787
            Serializer serializer = new Serializer();
1788
            serializer.SetOutputWriter(Console.Out);
1789
            serializer.SetOutputProperty(Serializer.INDENT, "yes");
1790

    
1791
            // Transform the source XML to System.out.
1792
            transformer.Run(serializer);
1793
        }
1794

    
1795
    }
1796

    
1797
    /// <summary>
1798
    /// A try-catch expression in the query, a feature of XQuery 3.0
1799
    /// to the C# application
1800
    /// </summary>
1801

    
1802
    public class XQueryTryCatch : Example
1803
    {
1804

    
1805
        public override string testName
1806
        {
1807
            get { return "XQueryTryCatch"; }
1808
        }
1809

    
1810
        /// <summary>
1811
        /// Show a query producing a single atomic value as its result and returning the value
1812
        /// to the C# application
1813
        /// </summary>
1814

    
1815
        public override void run(Uri samplesDir)
1816
        {
1817

    
1818
            String query = "xquery version '1.1'; try {doc('book.xml')}catch * {\"XQuery 1.1 catch clause - file not found.\"}";
1819
            Processor processor = new Processor();
1820

    
1821
            XQueryCompiler compiler = processor.NewXQueryCompiler();
1822
            compiler.XQueryLanguageVersion = "1.1";
1823
            XQueryExecutable exp = compiler.Compile(query);
1824
            XQueryEvaluator eval = exp.Load();
1825
            Serializer qout = new Serializer();
1826
            eval.Run(qout);
1827
        }
1828

    
1829
    }
1830

    
1831
    /// <summary>
1832
    /// Example extension function to compute a square root.
1833
    /// </summary>
1834

    
1835
    public class Sqrt : ExtensionFunctionDefinition
1836
    {
1837
        public override QName FunctionName
1838
        {
1839
            get
1840
            {
1841
                return new QName("http://example.math.co.uk/demo", "sqrt");
1842
            }
1843
        }
1844

    
1845
        public override int MinimumNumberOfArguments
1846
        {
1847
            get
1848
            {
1849
                return 1;
1850
            }
1851
        }
1852

    
1853
        public override int MaximumNumberOfArguments
1854
        {
1855
            get
1856
            {
1857
                return 1;
1858
            }
1859
        }
1860

    
1861
        public override XdmSequenceType[] ArgumentTypes
1862
        {
1863
            get
1864
            {
1865
                return new XdmSequenceType[]{
1866
                    new XdmSequenceType(XdmAtomicType.BuiltInAtomicType(QName.XS_DOUBLE), '?')
1867
                };
1868
            }
1869
        }
1870

    
1871
        public override XdmSequenceType ResultType(XdmSequenceType[] ArgumentTypes)
1872
        {
1873
            return new XdmSequenceType(XdmAtomicType.BuiltInAtomicType(QName.XS_DOUBLE), '?');
1874
        }
1875

    
1876
        public override bool TrustResultType
1877
        {
1878
            get
1879
            {
1880
                return true;
1881
            }
1882
        }
1883

    
1884

    
1885
        public override ExtensionFunctionCall MakeFunctionCall()
1886
        {
1887
            return new SqrtCall();
1888
        }
1889
    }
1890

    
1891
    internal class SqrtCall : ExtensionFunctionCall
1892
    {
1893
        public override IXdmEnumerator Call(IXdmEnumerator[] arguments, DynamicContext context)
1894
        {
1895
            Boolean exists = arguments[0].MoveNext();
1896
            if (exists)
1897
            {
1898
                XdmAtomicValue arg = (XdmAtomicValue)arguments[0].Current;
1899
                double val = (double)arg.Value;
1900
                double sqrt = System.Math.Sqrt(val);
1901
                XdmAtomicValue result = new XdmAtomicValue(sqrt);
1902
                return (IXdmEnumerator)result.GetEnumerator();
1903
            }
1904
            else
1905
            {
1906
                return EmptyEnumerator.INSTANCE;
1907
            }
1908
        }
1909

    
1910
    }
1911

    
1912
    /// <summary>
1913
    /// Example extension function to return the default namespace from the static context
1914
    /// </summary>
1915

    
1916
    public class DefaultNamespace : ExtensionFunctionDefinition
1917
    {
1918
        public override QName FunctionName
1919
        {
1920
            get
1921
            {
1922
                return new QName("http://example.env.co.uk/demo", "defaultNamespace");
1923
            }
1924
        }
1925

    
1926
        public override int MinimumNumberOfArguments
1927
        {
1928
            get
1929
            {
1930
                return 0;
1931
            }
1932
        }
1933

    
1934
        public override int MaximumNumberOfArguments
1935
        {
1936
            get
1937
            {
1938
                return 0;
1939
            }
1940
        }
1941

    
1942
        public override XdmSequenceType[] ArgumentTypes
1943
        {
1944
            get
1945
            {
1946
                return new XdmSequenceType[] { };
1947
            }
1948
        }
1949

    
1950
        public override bool DependsOnFocus
1951
        {
1952
            get
1953
            {
1954
                return true;
1955
                // actually it depends on the static context rather than the focus; but returning true is necessary
1956
                // to avoid the call being extracted to a global variable.
1957
            }
1958
        }
1959

    
1960
        public override XdmSequenceType ResultType(XdmSequenceType[] ArgumentTypes)
1961
        {
1962
            return new XdmSequenceType(XdmAtomicType.BuiltInAtomicType(QName.XS_STRING), '?');
1963
        }
1964

    
1965
        public override bool TrustResultType
1966
        {
1967
            get
1968
            {
1969
                return true;
1970
            }
1971
        }
1972

    
1973

    
1974
        public override ExtensionFunctionCall MakeFunctionCall()
1975
        {
1976
            return new DefaultNamespaceCall();
1977
        }
1978
    }
1979

    
1980
    internal class DefaultNamespaceCall : ExtensionFunctionCall
1981
    {
1982
        private string defaultNamespace;
1983

    
1984
        public override void SupplyStaticContext(StaticContext context)
1985
        {
1986
            defaultNamespace = context.GetNamespaceForPrefix("");
1987
        }
1988

    
1989
        public override IXdmEnumerator Call(IXdmEnumerator[] arguments, DynamicContext context)
1990
        {
1991
            if (defaultNamespace != null)
1992
            {
1993
                return (IXdmEnumerator)new XdmAtomicValue(defaultNamespace).GetEnumerator();
1994
            }
1995
            else
1996
            {
1997
                return EmptyEnumerator.INSTANCE;
1998
            }
1999
        }
2000

    
2001
    }
2002

    
2003
    /// <summary>
2004
    /// Show a query producing a document as its result and serializing this to a FileStream
2005
    /// </summary>
2006

    
2007
    public class XQueryToStream : Example
2008
    {
2009

    
2010
        public override string testName
2011
        {
2012
            get { return "XQueryToStream"; }
2013
        }
2014

    
2015
        /// <summary>
2016
        /// Show a query producing a document as its result and serializing this to a FileStream
2017
        /// </summary>
2018

    
2019
        public override void run(Uri samplesDir)
2020
        {
2021
            Processor processor = new Processor();
2022
            XQueryCompiler compiler = processor.NewXQueryCompiler();
2023
            compiler.BaseUri = samplesDir.ToString();
2024
            compiler.DeclareNamespace("saxon", "http://saxon.sf.net/");
2025
            XQueryExecutable exp = compiler.Compile("<saxon:example>{static-base-uri()}</saxon:example>");
2026
            XQueryEvaluator eval = exp.Load();
2027
            Serializer qout = new Serializer();
2028
            qout.SetOutputProperty(Serializer.METHOD, "xml");
2029
            qout.SetOutputProperty(Serializer.INDENT, "yes");
2030
            qout.SetOutputProperty(Serializer.SAXON_INDENT_SPACES, "1");
2031
            qout.SetOutputStream(new FileStream("testoutput.xml", FileMode.Create, FileAccess.Write));
2032
            Console.WriteLine("Output written to testoutput.xml");
2033
            eval.Run(qout);
2034
        }
2035

    
2036
    }
2037

    
2038
    /// <summary>
2039
    /// Show a query producing a single atomic value as its result and returning the value
2040
    /// to the C# application
2041
    /// </summary>
2042

    
2043
    public class XQueryToAtomicValue : Example
2044
    {
2045

    
2046
        public override string testName
2047
        {
2048
            get { return "XQueryToAtomicValue"; }
2049
        }
2050

    
2051
        /// <summary>
2052
        /// Show a query producing a single atomic value as its result and returning the value
2053
        /// to the C# application
2054
        /// </summary>
2055

    
2056
        public override void run(Uri samplesDir)
2057
        {
2058
            Processor processor = new Processor();
2059
            XQueryCompiler compiler = processor.NewXQueryCompiler();
2060
            XQueryExecutable exp = compiler.Compile("avg(for $i in 1 to 10 return $i * $i)");
2061
            XQueryEvaluator eval = exp.Load();
2062
            XdmAtomicValue result = (XdmAtomicValue)eval.EvaluateSingle();
2063
            Console.WriteLine("Result type: " + result.Value.GetType());
2064
            Console.WriteLine("Result value: " + (decimal)result.Value);
2065
        }
2066

    
2067
    }
2068

    
2069
    /// <summary>
2070
    /// Show a query producing a DOM as its input and producing a DOM as its output
2071
    /// </summary>
2072

    
2073
    public class XQueryToDom : Example
2074
    {
2075

    
2076
        public override string testName
2077
        {
2078
            get { return "XQueryToDom"; }
2079
        }
2080

    
2081
        /// <summary>
2082
        /// Show a query producing a DOM as its input and producing a DOM as its output
2083
        /// </summary>
2084

    
2085
        public override void run(Uri samplesDir)
2086
        {
2087
            Processor processor = new Processor();
2088

    
2089
            XmlDocument input = new XmlDocument();
2090
            input.Load(new Uri(samplesDir, "data/books.xml").ToString());
2091
            XdmNode indoc = processor.NewDocumentBuilder().Build(new XmlNodeReader(input));
2092

    
2093
            XQueryCompiler compiler = processor.NewXQueryCompiler();
2094
            XQueryExecutable exp = compiler.Compile("<doc>{reverse(/*/*)}</doc>");
2095
            XQueryEvaluator eval = exp.Load();
2096
            eval.ContextItem = indoc;
2097
            DomDestination qout = new DomDestination();
2098
            eval.Run(qout);
2099
            XmlDocument outdoc = qout.XmlDocument;
2100
            Console.WriteLine(outdoc.OuterXml);
2101
        }
2102

    
2103
    }
2104

    
2105
    /// <summary>
2106
    /// Show a query producing a Saxon tree as its input and producing a Saxon tree as its output
2107
    /// </summary>
2108

    
2109
    public class XQueryToXdm : Example
2110
    {
2111

    
2112
        public override string testName
2113
        {
2114
            get { return "XQueryToXdm"; }
2115
        }
2116

    
2117
        /// <summary>
2118
        /// Show a query producing a Saxon tree as its input and producing a Saxon tree as its output
2119
        /// </summary>
2120

    
2121
        public override void run(Uri samplesDir)
2122
        {
2123
            Processor processor = new Processor();
2124

    
2125
            DocumentBuilder loader = processor.NewDocumentBuilder();
2126
            loader.BaseUri = new Uri(samplesDir, "data/books.xml");
2127
            XdmNode indoc = loader.Build(loader.BaseUri);
2128

    
2129
            XQueryCompiler compiler = processor.NewXQueryCompiler();
2130
            XQueryExecutable exp = compiler.Compile("<doc>{reverse(/*/*)}</doc>");
2131
            XQueryEvaluator eval = exp.Load();
2132
            eval.ContextItem = indoc;
2133
            XdmDestination qout = new XdmDestination();
2134
            eval.Run(qout);
2135
            XdmNode outdoc = qout.XdmNode;
2136
            Console.WriteLine(outdoc.OuterXml);
2137
        }
2138

    
2139
    }
2140

    
2141
    /// <summary>
2142
    /// Show a query making a direct call to a user-defined function defined in the query
2143
    /// </summary>
2144

    
2145
    public class XQueryCallFunction : Example
2146
    {
2147

    
2148
        public override string testName
2149
        {
2150
            get { return "XQueryCallFunction"; }
2151
        }
2152

    
2153
        /// <summary>
2154
        /// Show a direct call on a user-defined function defined within the query
2155
        /// </summary>
2156

    
2157
        public override void run(Uri samplesDir)
2158
        {
2159
            Processor processor = new Processor();
2160

    
2161
            XQueryCompiler qc = processor.NewXQueryCompiler();
2162
            Uri uri = new Uri(samplesDir, "data/books.xml");
2163
            XQueryExecutable exp1 = qc.Compile("declare namespace f='f.ns';" +
2164
                   "declare variable $z := 1 + xs:integer(doc-available('" + uri.ToString() + "'));" +
2165
                   "declare variable $p as xs:integer external;" +
2166
                   "declare function f:t1($v1 as xs:integer) { " +
2167
                   "   $v1 div $z + $p" +
2168
                   "};" +
2169
                   "10");
2170
            XQueryEvaluator ev = exp1.Load();
2171
            ev.SetExternalVariable(new QName("", "p"), new XdmAtomicValue(39));
2172
            XdmValue v1 = new XdmAtomicValue(10);
2173
            XdmValue result = ev.CallFunction(new QName("f.ns", "f:t1"), new XdmValue[] { v1 });
2174
            Console.WriteLine("First result (expected 44): " + result.ToString());
2175
            v1 = new XdmAtomicValue(20);
2176
            result = ev.CallFunction(new QName("f.ns", "f:t1"), new XdmValue[] { v1 });
2177
            Console.WriteLine("Second result (expected 49): " + result.ToString());
2178
        }
2179

    
2180
    }
2181

    
2182

    
2183

    
2184
    /// <summary>
2185
    /// Show a query producing a sequence as its result and returning the sequence
2186
    /// to the C# application in the form of an iterator. For each item in the
2187
    /// result, its string value is output.
2188
    /// </summary>
2189

    
2190
    public class XQueryToSequence : Example
2191
    {
2192

    
2193
        public override string testName
2194
        {
2195
            get { return "XQueryToSequence"; }
2196
        }
2197

    
2198
        /// <summary>
2199
        /// Show a query producing a sequence as its result and returning the sequence
2200
        /// to the C# application in the form of an iterator. For each item in the
2201
        /// result, its string value is output.
2202
        /// </summary>
2203

    
2204
        public override void run(Uri samplesDir)
2205
        {
2206
            Processor processor = new Processor();
2207
            XQueryCompiler compiler = processor.NewXQueryCompiler();
2208
            XQueryExecutable exp = compiler.Compile("for $i in 1 to 10 return $i * $i");
2209
            XQueryEvaluator eval = exp.Load();
2210
            XdmValue value = eval.Evaluate();
2211
            IEnumerator e = value.GetEnumerator();
2212
            while (e.MoveNext())
2213
            {
2214
                XdmItem item = (XdmItem)e.Current;
2215
                Console.WriteLine(item.ToString());
2216
            }
2217

    
2218
        }
2219

    
2220
    }
2221

    
2222
    /// <summary>
2223
    /// Show a query reading an input document using an XmlReader (the .NET XML parser)
2224
    /// </summary>
2225

    
2226
    public class XQueryFromXmlReader : Example
2227
    {
2228

    
2229
        public override string testName
2230
        {
2231
            get { return "XQueryFromXmlReader"; }
2232
        }
2233

    
2234
        /// <summary>
2235
        /// Show a query reading an input document using an XmlReader (the .NET XML parser)
2236
        /// </summary>
2237

    
2238
        public override void run(Uri samplesDir)
2239
        {
2240
            Processor processor = new Processor();
2241

    
2242
            String inputFileName = new Uri(samplesDir, "data/books.xml").ToString();
2243
            XmlTextReader reader = new XmlTextReader(inputFileName,
2244
                UriConnection.getReadableUriStream(new Uri(samplesDir, "data/books.xml")));
2245
            //new FileStream(inputFileName, FileMode.Open, FileAccess.Read));
2246
            reader.Normalization = true;
2247

    
2248
            // add a validating reader - not to perform validation, but to expand entity references
2249
            XmlValidatingReader validator = new XmlValidatingReader(reader);
2250
            validator.ValidationType = ValidationType.None;
2251

    
2252
            XdmNode doc = processor.NewDocumentBuilder().Build(validator);
2253

    
2254
            XQueryCompiler compiler = processor.NewXQueryCompiler();
2255
            XQueryExecutable exp = compiler.Compile("/");
2256
            XQueryEvaluator eval = exp.Load();
2257
            eval.ContextItem = doc;
2258
            Serializer qout = new Serializer();
2259
            qout.SetOutputProperty(Serializer.METHOD, "xml");
2260
            qout.SetOutputProperty(Serializer.INDENT, "yes");
2261
            qout.SetOutputStream(new FileStream("testoutput2.xml", FileMode.Create, FileAccess.Write));
2262
            eval.Run(qout);
2263
        }
2264

    
2265
    }
2266

    
2267
    /// <summary>
2268
    /// Show a query producing a sequence as its result and returning the sequence
2269
    /// to the C# application in the form of an iterator. The sequence is then
2270
    /// output by serializing each item individually, with each item on a new line.
2271
    /// </summary>
2272

    
2273
    public class XQueryToSerializedSequence : Example
2274
    {
2275

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

    
2281
        /// <summary>
2282
        /// Show a query producing a sequence as its result and returning the sequence
2283
        /// to the C# application in the form of an iterator. The sequence is then
2284
        /// output by serializing each item individually, with each item on a new line.
2285
        /// </summary>
2286

    
2287
        public override void run(Uri samplesDir)
2288
        {
2289
            Processor processor = new Processor();
2290
            String inputFileName = new Uri(samplesDir, "data/books.xml").ToString();
2291
            //XmlTextReader reader = new XmlTextReader(inputFileName,
2292
            //    new FileStream(inputFileName, FileMode.Open, FileAccess.Read));
2293
            XmlTextReader reader = new XmlTextReader(inputFileName,
2294
                UriConnection.getReadableUriStream(new Uri(samplesDir, "data/books.xml")));
2295
            reader.Normalization = true;
2296

    
2297
            // add a validating reader - not to perform validation, but to expand entity references
2298
            XmlValidatingReader validator = new XmlValidatingReader(reader);
2299
            validator.ValidationType = ValidationType.None;
2300

    
2301
            XdmNode doc = processor.NewDocumentBuilder().Build(reader);
2302
            XQueryCompiler compiler = processor.NewXQueryCompiler();
2303
            XQueryExecutable exp = compiler.Compile("//ISBN");
2304

    
2305
            XQueryEvaluator eval = exp.Load();
2306
            eval.ContextItem = doc;
2307

    
2308
            foreach (XdmNode node in eval)
2309
            {
2310
                Console.WriteLine(node.OuterXml);
2311
            }
2312
        }
2313

    
2314
    }
2315

    
2316
    /// <summary>
2317
    /// Show a query that takes a parameter (external variable) as input.
2318
    /// The query produces a single atomic value as its result and returns the value
2319
    /// to the C# application. 
2320
    /// </summary>
2321

    
2322
    public class XQueryUsingParameter : Example
2323
    {
2324

    
2325
        public override string testName
2326
        {
2327
            get { return "XQueryUsingParameter"; }
2328
        }
2329

    
2330
        /// <summary>
2331
        /// Show a query that takes a parameter (external variable) as input.
2332
        /// The query produces a single atomic value as its result and returns the value
2333
        /// to the C# application. 
2334
        /// </summary>
2335

    
2336
        public override void run(Uri samplesDir)
2337
        {
2338
            Processor processor = new Processor();
2339
            XQueryCompiler compiler = processor.NewXQueryCompiler();
2340
            compiler.DeclareNamespace("p", "http://saxon.sf.net/ns/p");
2341
            XQueryExecutable exp = compiler.Compile(
2342
                    "declare variable $p:in as xs:integer external; $p:in * $p:in");
2343
            XQueryEvaluator eval = exp.Load();
2344
            eval.SetExternalVariable(new QName("http://saxon.sf.net/ns/p", "p:in"), new XdmAtomicValue(12));
2345
            XdmAtomicValue result = (XdmAtomicValue)eval.EvaluateSingle();
2346
            Console.WriteLine("Result type: " + result.Value.GetType());
2347
            Console.WriteLine("Result value: " + (long)result.Value);
2348
        }
2349

    
2350
    }
2351

    
2352
    /// <summary>
2353
    /// Show a query consisting of two modules, using a QueryResolver to resolve
2354
    /// the "import module" declaration
2355
    /// </summary>
2356

    
2357
    public class XQueryMultiModule : Example
2358
    {
2359

    
2360
        public override string testName
2361
        {
2362
            get { return "XQueryMultiModule"; }
2363
        }
2364

    
2365
        /// <summary>
2366
        /// Show a query consisting of two modules, using a QueryResolver to resolve
2367
        /// the "import module" declaration
2368
        /// </summary>
2369

    
2370
        public override void run(Uri samplesDir)
2371
        {
2372

    
2373
            String mod1 = "import module namespace m2 = 'http://www.example.com/module2';" +
2374
                          "m2:square(3)";
2375

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

    
2379
            Processor processor = new Processor();
2380
            XQueryCompiler compiler = processor.NewXQueryCompiler();
2381

    
2382
            InlineModuleResolver resolver = new InlineModuleResolver();
2383
            resolver.AddModule(new Uri("http://www.example.com/module2"), mod2);
2384
            compiler.QueryResolver = resolver;
2385
            XQueryExecutable exp = compiler.Compile(mod1);
2386
            XQueryEvaluator eval = exp.Load();
2387

    
2388
            XdmAtomicValue result = (XdmAtomicValue)eval.EvaluateSingle();
2389
            Console.WriteLine("Result type: " + result.Value.GetType());
2390
            Console.WriteLine("Result value: " + (long)result.Value);
2391
        }
2392

    
2393
        // A simple QueryResolver designed to show that the actual query
2394
        // text can come from anywhere: in this case, the resolver maintains
2395
        // a simple mapping of module URIs onto strings.
2396

    
2397
        public class InlineModuleResolver : IQueryResolver
2398
        {
2399

    
2400
            private Hashtable modules = new Hashtable();
2401

    
2402
            public void AddModule(Uri moduleName, String moduleText)
2403
            {
2404
                modules.Add(moduleName, moduleText);
2405
            }
2406

    
2407
            public Uri[] GetModules(String moduleUri, Uri baseUri, String[] locationHints)
2408
            {
2409
                Uri[] result = { new Uri(moduleUri) };
2410
                return result;
2411
            }
2412

    
2413
            public Object GetEntity(Uri absoluteUri)
2414
            {
2415
                return modules[absoluteUri];
2416
            }
2417
        }
2418

    
2419
    }
2420

    
2421
    /// <summary>
2422
    /// Demonstrate XQuery extensibility using user-written extension functions
2423
    /// </summary>
2424

    
2425
    public class XQueryExtensibility : Example
2426
    {
2427

    
2428
        public override string testName
2429
        {
2430
            get { return "XQueryExtensibility"; }
2431
        }
2432

    
2433
        /// <summary>
2434
        /// Demonstrate XQuery extensibility using user-written extension functions
2435
        /// </summary>
2436
        /// <remarks>Note: If SamplesExtensions is compiled to a different assembly than ExamplesEE, use 
2437
        /// the namespace URI clitype:SampleExtensions.SampleExtensions?asm=ASSEMBLY_NAME_HERE
2438
        /// </remarks>
2439

    
2440
        public override void run(Uri samplesDir)
2441
        {
2442
            String query =
2443
                "declare namespace ext = \"clitype:SampleExtensions.SampleExtensions?asm=ExamplesEE\";" +
2444
                "<out>" +
2445
                "  <addition>{ext:add(2,2)}</addition>" +
2446
                "  <average>{ext:average((1,2,3,4,5,6))}</average>" +
2447
                "  <language>{ext:hostLanguage()}</language>" +
2448
                "</out>";
2449

    
2450
            Processor processor = new Processor();
2451
            XQueryCompiler compiler = processor.NewXQueryCompiler();
2452
            XQueryExecutable exp = compiler.Compile(query);
2453
            XQueryEvaluator eval = exp.Load();
2454
            Serializer qout = new Serializer();
2455
            eval.Run(qout);
2456
        }
2457

    
2458
    }
2459

    
2460
    /// <summary>
2461
    /// Demonstrate XQuery Update
2462
    /// </summary>
2463

    
2464
    public class XQueryUpdate : Example
2465
    {
2466

    
2467
        public override string testName
2468
        {
2469
            get { return "SA-XQueryUpdate"; }
2470
        }
2471

    
2472
        /// <summary>
2473
        /// Demonstrate XQuery Update
2474
        /// </summary>
2475

    
2476
        public override void run(Uri samplesDir)
2477
        {
2478
            Processor processor = new Processor(true);
2479

    
2480
            DocumentBuilder loader = processor.NewDocumentBuilder();
2481
            loader.BaseUri = new Uri(samplesDir, "data/books.xml");
2482
            loader.TreeModel = TreeModel.LinkedTree;
2483
            XdmNode indoc = loader.Build(new Uri(samplesDir, "data/books.xml"));
2484

    
2485
            Console.Out.WriteLine("=========== BEFORE UPDATE ===========");
2486

    
2487
            Serializer serializer0 = new Serializer();
2488
            serializer0.SetOutputProperty(Serializer.METHOD, "xml");
2489
            serializer0.SetOutputProperty(Serializer.INDENT, "yes");
2490
            serializer0.SetOutputWriter(Console.Out);
2491
            processor.WriteXdmValue(indoc, serializer0);
2492

    
2493
            String query =
2494
                "for $i in //PRICE return \n" +
2495
                "replace value of node $i with $i - 0.05";
2496

    
2497
            XQueryCompiler compiler = processor.NewXQueryCompiler();
2498
            compiler.UpdatingEnabled = true;
2499
            XQueryExecutable exp = compiler.Compile(query);
2500
            XQueryEvaluator eval = exp.Load();
2501
            eval.ContextItem = indoc;
2502
            XdmNode[] updatedNodes = eval.RunUpdate();
2503
            foreach (XdmNode root in updatedNodes)
2504
            {
2505
                Uri documentUri = root.DocumentUri;
2506
                if (documentUri != null && documentUri.Scheme == "file")
2507
                {
2508
                    Stream stream = UriConnection.getWritableUriStream(documentUri);
2509
                    Serializer serializer = new Serializer();
2510
                    serializer.SetOutputProperty(Serializer.METHOD, "xml");
2511
                    serializer.SetOutputProperty(Serializer.INDENT, "yes");
2512
                    serializer.SetOutputStream(stream);
2513
                    processor.WriteXdmValue(root, serializer);
2514
                }
2515
            }
2516

    
2517
            Console.Out.WriteLine("=========== AFTER UPDATE ===========");
2518

    
2519
            processor.WriteXdmValue(indoc, serializer0);
2520
        }
2521
    }
2522

    
2523
    /// <summary>
2524
    /// A try-catch expression in the query, a feature of XQuery 3.0
2525
    /// to the C# application
2526
    /// </summary>
2527

    
2528
    public class XQuerySchemaAware : Example
2529
    {
2530

    
2531
        public override string testName
2532
        {
2533
            get { return "XQuerySchemaAware"; }
2534
        }
2535

    
2536
        public override void run(Uri samplesDir)
2537
        {
2538

    
2539
            String query = "import schema default element namespace \"\" at \"" + samplesDir + "\\data\\books.xsd\";\n" +
2540
                            "for $integer in (validate { doc(\"" + samplesDir + "\\data\\books.xml\") })//schema-element(ITEM)\n" +
2541
                                "return <OUTPUT>{$integer}</OUTPUT>";
2542
            Processor processor = new Processor();
2543

    
2544
            XQueryCompiler compiler = processor.NewXQueryCompiler();
2545
            compiler.XQueryLanguageVersion = "1.0";
2546
            XQueryExecutable exp = compiler.Compile(query);
2547
            XQueryEvaluator eval = exp.Load();
2548
            Serializer qout = new Serializer();
2549
            eval.Run(qout);
2550
        }
2551

    
2552
    }
2553

    
2554
    /// <summary>
2555
    /// Show XPath (Schema aware) example
2556
    /// </summary>
2557

    
2558
    public class XPathSchemaAware : Example
2559
    {
2560

    
2561
        public override string testName
2562
        {
2563
            get { return "XPathSchemaAware"; }
2564
        }
2565

    
2566

    
2567
        public override void run(Uri samplesDir)
2568
        {
2569
            Processor processor = new Processor(true);
2570

    
2571

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

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

    
2576
            // add a reader
2577
            XmlReader xmlReader = XmlReader.Create(UriConnection.getReadableUriStream(new Uri(samplesDir, "data/books.xml")));
2578

    
2579
            DocumentBuilder builder = processor.NewDocumentBuilder();
2580

    
2581
            builder.SchemaValidationMode = SchemaValidationMode.Strict;
2582
            XdmNode doc = builder.Build(xmlReader);
2583

    
2584
            XPathCompiler compiler = processor.NewXPathCompiler();
2585
            compiler.ImportSchemaNamespace("");
2586
            XPathExecutable exp = compiler.Compile("if (//ITEM[@CAT='MMP']/QUANTITY instance of element(*,xs:integer)*) then 'true' else 'false'");
2587
            XPathSelector eval = exp.Load();
2588
            eval.ContextItem = doc;
2589
            XdmAtomicValue result = (XdmAtomicValue)eval.EvaluateSingle();
2590
            Console.WriteLine("Result type: " + result.ToString());
2591
        }
2592

    
2593
    }
2594

    
2595
    /// <summary>
2596
    /// Show XSLT streaming of document
2597
    /// </summary>
2598

    
2599
    public class XsltStreamDoc : Example
2600
    {
2601

    
2602
        public override string testName
2603
        {
2604
            get { return "XsltStreamDoc"; }
2605
        }
2606

    
2607
        public override void run(Uri samplesDir)
2608
        {
2609
            Processor processor = new Processor(true);
2610

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

    
2617
            // Create a transformer for the stylesheet.
2618
            XsltTransformer transformer = processor.NewXsltCompiler().Compile(new StringReader(s)).Load();
2619
            transformer.InitialTemplate = new QName("main");
2620

    
2621
            // Create a serializer
2622
            Serializer serializer = new Serializer();
2623
            serializer.SetOutputWriter(Console.Out);
2624
            //  serializer.SetOutputProperty(Serializer.INDENT, "yes");
2625

    
2626
            // Transform the source XML to System.out.
2627
            transformer.Run(serializer);
2628

    
2629

    
2630
        }
2631

    
2632
    }
2633

    
2634
    /// <summary>
2635
    /// Show validation of an instance document against a schema
2636
    /// </summary>
2637

    
2638
    public class Validate : Example
2639
    {
2640

    
2641
        public override string testName
2642
        {
2643
            get { return "EE-Validate"; }
2644
        }
2645

    
2646
        /// <summary>
2647
        /// Show validation of an instance document against a schema
2648
        /// </summary>
2649

    
2650
        public override void run(Uri samplesDir)
2651
        {
2652
            // Load a schema
2653

    
2654
            Processor processor;
2655
            try
2656
            {
2657
                processor = new Processor(true);
2658
            }
2659
            catch (Exception err)
2660
            {
2661
                Console.WriteLine(err);
2662
                Console.WriteLine("Failed to load Saxon-EE (use -HE option to run Saxon-HE tests only)");
2663
                return;
2664
            }
2665
            processor.SetProperty("http://saxon.sf.net/feature/timing", "true");
2666
            processor.SetProperty("http://saxon.sf.net/feature/validation-warnings", "true");
2667
            SchemaManager manager = processor.SchemaManager;
2668
            manager.XsdVersion = "1.1";
2669
            manager.ErrorList = new ArrayList();
2670
            Uri schemaUri = new Uri(samplesDir, "data/books.xsd");
2671

    
2672
            try
2673
            {
2674
                manager.Compile(schemaUri);
2675
            }
2676
            catch (Exception e)
2677
            {
2678
                Console.WriteLine(e);
2679
                Console.WriteLine("Schema compilation failed with " + manager.ErrorList.Count + " errors");
2680
                foreach (StaticError error in manager.ErrorList)
2681
                {
2682
                    Console.WriteLine("At line " + error.LineNumber + ": " + error.Message);
2683
                }
2684
                return;
2685
            }
2686

    
2687

    
2688
            // Use this to validate an instance document
2689

    
2690
            SchemaValidator validator = manager.NewSchemaValidator();
2691
            //Uri instanceUri = new Uri(samplesDir, "data/books-invalid.xml");
2692
            //validator.SetSource(instanceUri);
2693
            XmlReader xmlReader = XmlReader.Create(samplesDir + "data/books-invalid.xml");
2694
            validator.SetSource(xmlReader);
2695
            validator.ErrorList = new ArrayList();
2696
            XdmDestination psvi = new XdmDestination();
2697
            validator.SetDestination(psvi);
2698

    
2699
            try
2700
            {
2701
                validator.Run();
2702
            }
2703
            catch (Exception e)
2704
            {
2705
                Console.WriteLine(e);
2706
                Console.WriteLine("Instance validation failed with " + validator.ErrorList.Count + " errors");
2707
                foreach (StaticError error in validator.ErrorList)
2708
                {
2709
                    Console.WriteLine("At line " + error.LineNumber + ": " + error.Message);
2710
                }
2711
                return;
2712
            }
2713

    
2714
            // Run a query on the result to check that it has type annotations
2715

    
2716
            XQueryCompiler xq = processor.NewXQueryCompiler();
2717
            XQueryEvaluator xv = xq.Compile("data((//PRICE)[1]) instance of xs:decimal").Load();
2718
            xv.ContextItem = psvi.XdmNode;
2719
            Console.WriteLine("Price is decimal? " + xv.EvaluateSingle().ToString());
2720
        }
2721
    }
2722

    
2723

    
2724

    
2725
    public class UriConnection
2726
    {
2727

    
2728
        // Get a stream for reading from a file:// URI
2729

    
2730
        public static Stream getReadableUriStream(Uri uri)
2731
        {
2732
            WebRequest request = (WebRequest)WebRequest.Create(uri);
2733
            return request.GetResponse().GetResponseStream();
2734
        }
2735

    
2736
        // Get a stream for writing to a file:// URI
2737

    
2738
        public static Stream getWritableUriStream(Uri uri)
2739
        {
2740
            FileWebRequest request = (FileWebRequest)WebRequest.CreateDefault(uri);
2741
            request.Method = "POST";
2742
            return request.GetRequestStream();
2743
        }
2744
    }
2745

    
2746
    ///
2747
    /// A sample XmlResolver. In the case of a URI ending with ".txt", it returns the
2748
    /// URI itself, wrapped as an XML document. In the case of the URI "empty.xslt", it returns an empty
2749
    /// stylesheet. In all other cases, it returns null, which has the effect of delegating
2750
    /// processing to the standard XmlResolver.
2751
    ///
2752

    
2753
    public class UserXmlResolver : XmlUrlResolver
2754
    {
2755

    
2756
        public String Message = null;
2757

    
2758
        public override object GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn)
2759
        {
2760
            if (Message != null)
2761
            {
2762
                Console.WriteLine(Message + absoluteUri + " (role=" + role + ")");
2763
            }
2764

    
2765
            if (absoluteUri.ToString().EndsWith(".txt"))
2766
            {
2767
                MemoryStream ms = new MemoryStream();
2768
                StreamWriter tw = new StreamWriter(ms);
2769
                tw.Write("<uri>");
2770
                tw.Write(absoluteUri);
2771
                tw.Write("</uri>");
2772
                tw.Flush();
2773
                return new MemoryStream(ms.GetBuffer(), 0, (int)ms.Length);
2774
            }
2775
            if (absoluteUri.ToString().EndsWith("empty.xslt"))
2776
            {
2777
                String ss = "<transform xmlns='http://www.w3.org/1999/XSL/Transform' version='2.0'/>";
2778
                MemoryStream ms = new MemoryStream();
2779
                StreamWriter tw = new StreamWriter(ms);
2780
                tw.Write(ss);
2781
                tw.Flush();
2782
                return new MemoryStream(ms.GetBuffer(), 0, (int)ms.Length);
2783
            }
2784
            else
2785
            {
2786
                return null;
2787
            }
2788
        }
2789
    }
2790

    
2791
    public class UserResultDocumentHandler : IResultDocumentHandler
2792
    {
2793

    
2794
        private Hashtable results;
2795

    
2796
        public UserResultDocumentHandler(Hashtable table)
2797
        {
2798
            this.results = table;
2799
        }
2800

    
2801
        public XmlDestination HandleResultDocument(string href, Uri baseUri)
2802
        {
2803
            DomDestination destination = new DomDestination();
2804
            results[href] = destination;
2805
            return destination;
2806
        }
2807

    
2808
    }
2809
}
2810

    
2811

    
2812
//
2813
// The contents of this file are subject to the Mozilla Public License Version 1.0 (the "License");
2814
// you may not use this file except in compliance with the License. You may obtain a copy of the
2815
// License at http://www.mozilla.org/MPL/
2816
//
2817
// Software distributed under the License is distributed on an "AS IS" basis,
2818
// WITHOUT WARRANTY OF ANY KIND, either express or implied.
2819
// See the License for the specific language governing rights and limitations under the License.
2820
//
2821
// The Original Code is: all this file.
2822
//
2823
// The Initial Developer of the Original Code is Michael H. Kay.
2824
//
2825
// Portions created by (your name) are Copyright (C) (your legal entity). All Rights Reserved.
2826
//
2827
// Contributor(s): none.
2828
//
2829

    
2830

    
2831

    
(2-2/14)