Project

Profile

Help

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

he / tags / 9.6.0.7 / hen / csource / samples / Examples.cs @ aa733b18

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
public class Examples
10
{
11

    
12
    /// <summary>
13
    /// Run Saxon XSLT and XQuery sample applications
14
    /// </summary>
15
    /// <param name="argv">
16
    /// <para>Options:</para>
17
    /// <list>
18
    /// <item>-SA             run all tests including Saxon-SA tests (default)</item>
19
    /// <item>-B              run Saxon-B tests only</item>
20
    /// <item>-test:testname  run a specific test</item>
21
    /// <item>-dir:samplesdir directory containing the sample data files (default %SAXON_HOME%/samples)</item>
22
    /// <item>-ask:yes|no     indicates whether to prompt for confirmation after each test (default yes)</item>
23
    /// </list>
24
    /// </param>
25

    
26

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

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

    
76
        Boolean ask = true;
77
        String test = "all";
78

    
79
        String samplesPath = null;
80
        Uri samplesDir;
81

    
82
        foreach (String s in argv)
83
        {
84
            if (s == "-HE")
85
            {
86
                test = "HE";
87
            }
88
            else if (s == "-EE")
89
            {
90
                test = "all";
91
            }
92
            else if (s.StartsWith("-test:"))
93
            {
94
                test = s.Substring(6);
95
            }
96
            else if (s.StartsWith("-dir:"))
97
            {
98
                samplesPath = s.Substring(5);
99
            }
100
            else if (s == "-ask:yes")
101
            {
102
                // no action
103
            }
104
            else if (s == "-ask:no")
105
            {
106
                ask = false;
107
            }
108
            else if (s == "-?")
109
            {
110
                Console.WriteLine("Examples (-B|-SA) -dir:samples -test:testname -ask:yes|no");
111
            }
112
            else
113
            {
114
                Console.WriteLine("Unrecognized Argument: " + s);
115
                return;
116
            }
117
        }
118
        if (samplesPath != null) 
119
        {
120
            if (samplesPath.StartsWith("file:///"))
121
            {
122
                samplesPath = samplesPath.Substring(8);
123
            } else if (samplesPath.StartsWith("file:/")) {
124
                samplesPath = samplesPath.Substring(6);
125
            }
126
            
127
        }
128
        else
129
        {
130
            String home = Environment.GetEnvironmentVariable("SAXON_HOME");
131
            if (home == null)
132
            {
133
                Console.WriteLine("No input directory supplied, and SAXON_HOME is not set");
134
                return;
135
            }
136
            else
137
            {
138
                if (!(home.EndsWith("/") || home.EndsWith("\\")))
139
                {
140
                    home = home + "/";
141
                }
142
                samplesPath = home + "samples/";
143
            }
144
        }
145

    
146
        if (!(samplesPath.EndsWith("/") || samplesPath.EndsWith("\\")))
147
        {
148
            samplesPath = samplesPath + "/";
149
        }
150

    
151
        if (!File.Exists(samplesPath + "data/books.xml")) {
152
            Console.WriteLine("Supplied samples directory " + samplesPath + " does not contain the Saxon sample data files");
153
            return;
154
        }
155
        
156
        samplesDir = new Uri(samplesPath);
157

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

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

    
203

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

    
215
/// <summary>
216
/// XPath expression selecting from a source document supplied as a URI
217
/// </summary>
218

    
219
public class XPathSimple : Example
220
{
221

    
222
    public override String testName
223
    {
224
        get { return "XPathSimple"; }
225
    }
226

    
227
    /// <summary>
228
    /// Run a transformation: simplest possible script
229
    /// </summary>
230

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

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

    
239
        // Create an XPath compiler
240
        XPathCompiler xpath = processor.NewXPathCompiler();
241

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

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

    
253
/// <summary>
254
/// XPath expression using variables (and no source document)
255
/// </summary>
256

    
257
public class XPathVariables : Example
258
{
259

    
260
    public override String testName
261
    {
262
        get { return "XPathVariables"; }
263
    }
264

    
265
    /// <summary>
266
    /// Run a transformation: simplest possible script
267
    /// </summary>
268

    
269
    public override void run(Uri samplesDir)
270
    {
271
        // Create a Processor instance.
272
        Processor processor = new Processor();
273

    
274
        // Create the XPath expression.
275
        XPathCompiler compiler = processor.NewXPathCompiler();
276
        compiler.DeclareVariable(new QName("", "a"));
277
        compiler.DeclareVariable(new QName("", "b"));
278
        XPathSelector selector = compiler.Compile("$a + $b").Load();
279

    
280
        // Set the values of the variables
281
        selector.SetVariable(new QName("", "a"), new XdmAtomicValue(2));
282
        selector.SetVariable(new QName("", "b"), new XdmAtomicValue(3));
283

    
284
        // Evaluate the XPath expression
285
        Console.WriteLine(selector.EvaluateSingle().ToString());
286
    }
287
}
288

    
289
/// <summary>
290
/// XPath expression using variables without explicit declaration
291
/// </summary>
292

    
293
public class XPathUndeclaredVariables : Example
294
{
295

    
296
    public override String testName
297
    {
298
        get { return "XPathUndeclaredVariables"; }
299
    }
300

    
301
    /// <summary>
302
    /// Execute an XPath expression containing undeclared variables
303
    /// </summary>
304

    
305
    public override void run(Uri samplesDir)
306
    {
307
        // Create a Processor instance.
308
        Processor processor = new Processor();
309

    
310
        // Create the XPath expression.
311
        XPathCompiler compiler = processor.NewXPathCompiler();
312
        compiler.AllowUndeclaredVariables = true;
313
        XPathExecutable expression = compiler.Compile("$a + $b");
314
        XPathSelector selector = expression.Load();
315

    
316
        // Set the values of the variables
317
        IEnumerator vars = expression.EnumerateExternalVariables();
318
        while (vars.MoveNext()) {
319
            selector.SetVariable((QName)vars.Current, new XdmAtomicValue(10));
320
        }
321

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

    
327
/// <summary>
328
/// XPath expression throwing a static error
329
/// </summary>
330

    
331
public class XPathWithStaticError : Example
332
{
333

    
334
    public override String testName
335
    {
336
        get { return "XPathWithStaticError"; }
337
    }
338

    
339
    /// <summary>
340
    /// Execute an XPath expression that throws a dynamic error, and catch the error
341
    /// </summary>
342

    
343
    public override void run(Uri samplesDir)
344
    {
345
        // Create a Processor instance.
346
        Processor processor = new Processor();
347

    
348
        // Create the XPath expression.
349
        XPathCompiler compiler = processor.NewXPathCompiler();
350
        compiler.AllowUndeclaredVariables = true;
351
        XPathExecutable expression = compiler.Compile("1 + unknown()");
352
        XPathSelector selector = expression.Load();
353

    
354
        // Evaluate the XPath expression
355
        Console.WriteLine(selector.EvaluateSingle().ToString());
356
    }
357
}
358

    
359
/// <summary>
360
/// XPath expression throwing a dynamic error
361
/// </summary>
362

    
363
public class XPathWithDynamicError : Example
364
{
365

    
366
    public override String testName
367
    {
368
        get { return "XPathWithDynamicError"; }
369
    }
370

    
371
    /// <summary>
372
    /// Execute an XPath expression that throws a dynamic error
373
    /// </summary>
374

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

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

    
386
        // Set the values of the variables
387
        selector.SetVariable(new QName("", "a"), new XdmAtomicValue(10));
388
        selector.SetVariable(new QName("", "b"), new XdmAtomicValue("Paris"));
389

    
390
        // Evaluate the XPath expression
391
        Console.WriteLine(selector.EvaluateSingle().ToString());
392
    }
393
}
394

    
395
/// <summary>
396
/// XSLT 2.0 transformation with source document and stylesheet supplied as URIs
397
/// </summary>
398

    
399
public class XsltSimple1 : Example {
400

    
401
    public override String testName {
402
        get { return "XsltSimple1"; }
403
    }
404

    
405
    /// <summary>
406
    /// Run a transformation: simplest possible script
407
    /// </summary>
408

    
409
    public override void run(Uri samplesDir)
410
    {
411
        // Create a Processor instance.
412
        Processor processor = new Processor();
413

    
414
        // Load the source document
415
        XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/books.xml"));
416

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

    
420
        // Set the root node of the source document to be the initial context node
421
        transformer.InitialContextNode = input;
422

    
423
        // Create a serializer, with output to the standard output stream
424
        Serializer serializer = new Serializer();
425
        serializer.SetOutputWriter(Console.Out);
426

    
427
        // Transform the source XML and serialize the result document
428
        transformer.Run(serializer);
429
    }
430
}
431

    
432
/// <summary>
433
/// Run a transformation, sending the serialized output to a file
434
/// </summary>
435

    
436
public class XsltSimple2 : Example {
437

    
438
    public override String testName {
439
        get { return "XsltSimple2"; }
440
    }
441

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

    
446

    
447
    public override void run(Uri samplesDir)
448
    {
449
        // Create a Processor instance.
450
        Processor processor = new Processor();
451

    
452
        // Load the source document
453
        XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/books.xml"));
454

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

    
458
        // Set the root node of the source document to be the initial context node
459
        transformer.InitialContextNode = input;
460

    
461
        // Create a serializer
462
        String outfile = "OutputFromXsltSimple2.xml";
463
        Serializer serializer = new Serializer();
464
        serializer.SetOutputStream(new FileStream(outfile, FileMode.Create, FileAccess.Write));
465

    
466
        // Transform the source XML to System.out.
467
        transformer.Run(serializer);
468

    
469
        Console.WriteLine("\nOutput written to " + outfile + "\n");
470
    }
471
}
472

    
473
/// <summary>
474
/// XSLT 2.0 transformation with source document and stylesheet supplied as URIs
475
/// </summary>
476

    
477
public class XsltSimple3 : Example
478
{
479

    
480
    public override String testName
481
    {
482
        get { return "XsltSimple3"; }
483
    }
484

    
485
    /// <summary>
486
    /// Run a transformation: supply input as a file
487
    /// </summary>
488

    
489
    public override void run(Uri samplesDir)
490
    {
491
        if (samplesDir.Scheme != Uri.UriSchemeFile)
492
        {
493
            Console.WriteLine("Supplied URI must be a file directory");
494
        }
495
        String dir = samplesDir.AbsolutePath;
496
        String sourceFile = dir + "data/books.xml";
497
        String styleFile = dir + "styles/books.xsl";
498

    
499
        // Create a Processor instance.
500
        Processor processor = new Processor();
501

    
502
        // Load the source document
503

    
504
        DocumentBuilder builder = processor.NewDocumentBuilder();
505
        builder.BaseUri = new Uri(samplesDir, "data/books.xml");
506

    
507
        XdmNode input = builder.Build(File.OpenRead(sourceFile));
508

    
509
        // Create a transformer for the stylesheet.
510
        XsltCompiler compiler = processor.NewXsltCompiler();
511
        compiler.BaseUri = new Uri(samplesDir, "styles/books.xsl");
512
        XsltTransformer transformer = compiler.Compile(File.OpenRead(styleFile)).Load();
513

    
514
        // Set the root node of the source document to be the initial context node
515
        transformer.InitialContextNode = input;
516

    
517
        // Create a serializer, with output to the standard output stream
518
        Serializer serializer = new Serializer();
519
        serializer.SetOutputWriter(Console.Out);
520

    
521
        // Transform the source XML and serialize the result document
522
        transformer.Run(serializer);
523
    }
524
}
525

    
526

    
527
/// <summary>
528
/// XSLT 2.0 transformation showing stripping of whitespace controlled by the stylesheet
529
/// </summary>
530

    
531
public class XsltStripSpace : Example
532
{
533

    
534
    public override String testName
535
    {
536
        get { return "XsltStripSpace"; }
537
    }
538

    
539
    /// <summary>
540
    /// Run a transformation: simplest possible script
541
    /// </summary>
542

    
543
    public override void run(Uri samplesDir)
544
    {
545
        Processor processor = new Processor();
546

    
547
        // Load the source document
548
        DocumentBuilder builder = processor.NewDocumentBuilder();
549
        builder.BaseUri = samplesDir;
550

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

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

    
568
        XsltCompiler compiler = processor.NewXsltCompiler();
569
        compiler.BaseUri = samplesDir;
570
        XsltTransformer transformer = compiler.Compile(new XmlTextReader(new StringReader(stylesheet))).Load();
571

    
572
        // Set the root node of the source document to be the initial context node
573
        transformer.InitialContextNode = input;
574

    
575
         // Create a serializer
576
        Serializer serializer = new Serializer();
577
        serializer.SetOutputWriter(Console.Out);
578

    
579
        // Transform the source XML to System.out.
580
        transformer.Run(serializer);
581
    }
582
}
583

    
584

    
585
/// <summary>
586
/// Run a transformation, compiling the stylesheet once and using it to transform two different source documents
587
/// </summary>
588

    
589
public class XsltReuseExecutable : Example {
590

    
591
    public override String testName {
592
        get { return "XsltReuseExecutable"; }
593
    }
594

    
595
    /// <summary>
596
    /// Show that a stylesheet can be compiled once (into an XsltExecutable) and run many times
597
    /// </summary>
598
    /// <param name="fileNames">
599
    /// 1. first source document
600
    /// 2. second source document
601
    /// 3. stylesheet used to transform both documents
602
    /// </param>
603

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

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

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

    
615
        String sourceFile1 = "data/books.xml";
616
        String sourceFile2 = "data/othello.xml";
617

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

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

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

    
637
public class XsltReuseTransformer : Example {
638

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

    
643
    /// <summary>
644
    /// Show that the XsltTransformer is serially reusable (we run it twice with different parameter settings)
645
    /// </summary>
646

    
647
    public override void run(Uri samplesDir)
648
    {
649
        // Create a Processor instance.
650
        Processor processor = new Processor();
651

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

    
655
        // Compile the stylesheet
656
        XsltExecutable exec = processor.NewXsltCompiler().Compile(new Uri(samplesDir, "styles/summarize.xsl"));
657

    
658
        // Create a transformer 
659
        XsltTransformer transformer = exec.Load();
660

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

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

    
677
/// <summary>
678
/// Run a sequence of transformations in a pipeline, each one acting as a filter
679
/// </summary>
680

    
681
public class XsltFilterChain : Example {
682

    
683
    public override String testName {
684
        get { return "XsltFilterChain"; }
685
    }
686

    
687
    /// <summary>
688
    /// Run the test
689
    /// </summary>
690

    
691
    public override void run(Uri samplesDir)
692
    {
693
 	    // Create a Processor instance.
694
        Processor processor = new Processor();
695

    
696
        // Load the source document
697
        XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/books.xml"));
698

    
699
        // Create a compiler
700
        XsltCompiler compiler = processor.NewXsltCompiler();
701

    
702
        // Compile all three stylesheets
703
        XsltTransformer transformer1 = compiler.Compile(new Uri(samplesDir, "styles/identity.xsl")).Load();
704
        XsltTransformer transformer2 = compiler.Compile(new Uri(samplesDir, "styles/books.xsl")).Load();
705
        XsltTransformer transformer3 = compiler.Compile(new Uri(samplesDir, "styles/summarize.xsl")).Load();
706

    
707
        // Now run them in series
708
        transformer1.InitialContextNode = input;
709
        XdmDestination results1 = new XdmDestination();
710
        transformer1.Run(results1);
711
        //Console.WriteLine("After phase 1:");
712
        //Console.WriteLine(results1.XdmNode.OuterXml);
713

    
714
        transformer2.InitialContextNode = results1.XdmNode;
715
        XdmDestination results2 = new XdmDestination();
716
        transformer2.Run(results2);
717
        //Console.WriteLine("After phase 2:");
718
        //Console.WriteLine(results2.XdmNode.OuterXml);
719

    
720
        transformer3.InitialContextNode = results2.XdmNode;
721
        //TextWriterDestination results3 = new TextWriterDestination(new XmlTextWriter(Console.Out));
722
        XdmDestination results3 = new XdmDestination();
723
        transformer3.Run(results3);
724
        Console.WriteLine("After phase 3:");
725
        Console.WriteLine(results3.XdmNode.OuterXml);
726
    }
727
}
728

    
729
/// <summary>
730
/// Transform from an XDM tree to an XDM tree
731
/// </summary>
732

    
733
public class XsltXdmToXdm : Example {
734

    
735
    public override String testName {
736
        get { return "XsltXdmToXdm"; }
737
    }
738

    
739
    /// <summary>
740
    /// Transform from an XDM tree to an XDM tree
741
    /// </summary>
742

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

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

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

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

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

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

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

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

    
778
public class XsltXdmElementToXdm : Example
779
{
780

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

    
786
    /// <summary>
787
    /// Run an XSLT transformation from an Xdm tree, starting at a node that is not the document node
788
    /// </summary>
789
    /// <param name="fileNames">
790
    /// 1. The source document
791
    /// 2. The stylesheet
792
    /// </param>
793

    
794
    public override void run(Uri samplesDir)
795
    {
796
        // Create a Processor instance.
797
        Processor processor = new Processor();
798

    
799
        // Load the source document
800
        XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/othello.xml"));
801

    
802
        // Navigate to the first grandchild
803
        XPathSelector eval = processor.NewXPathCompiler().Compile("/PLAY/FM[1]").Load();
804
        eval.ContextItem = input;
805
        input = (XdmNode)eval.EvaluateSingle();
806

    
807
        // Create an XSLT compiler
808
        XsltCompiler compiler = processor.NewXsltCompiler();
809

    
810
        // Compile the stylesheet
811
        XsltTransformer transformer = compiler.Compile(new Uri(samplesDir, "styles/summarize.xsl")).Load();
812

    
813
        // Run the transformation
814
        transformer.InitialContextNode = input;
815
        XdmDestination result = new XdmDestination();
816
        transformer.Run(result);
817

    
818
        // Serialize the result so we can see that it worked
819
        Console.WriteLine(result.XdmNode.OuterXml);
820
    }
821
}
822

    
823
/// <summary>
824
/// Run a transformation from a DOM (System.Xml.Document) input to a DOM output
825
/// </summary>
826

    
827
public class XsltDomToDom : Example {
828

    
829
    public override String testName {
830
        get { return "XsltDomToDom"; }
831
    }
832

    
833
    /// <summary>
834
    /// Run a transformation from a DOM (System.Xml.Document) input to a DOM output
835
    /// </summary>
836

    
837
    public override void run(Uri samplesDir)
838
    {
839

    
840
        // Create a Processor instance.
841
        Processor processor = new Processor();
842

    
843
        // Load the source document (in practice, it would already exist as a DOM)
844
        XmlDocument doc = new XmlDocument();
845
        doc.Load(new XmlTextReader(samplesDir.AbsolutePath + "data/othello.xml"));
846
        XdmNode input = processor.NewDocumentBuilder().Wrap(doc);
847

    
848
        // Create a compiler
849
        XsltCompiler compiler = processor.NewXsltCompiler();
850

    
851
        // Compile the stylesheet
852
        XsltTransformer transformer = compiler.Compile(new Uri(samplesDir, "styles/summarize.xsl")).Load();
853

    
854
        // Run the transformation
855
        transformer.InitialContextNode = input;
856
        DomDestination result = new DomDestination();
857
        transformer.Run(result);
858

    
859
        // Serialize the result so we can see that it worked
860
        Console.WriteLine(result.XmlDocument.OuterXml);
861
    }
862
}
863

    
864

    
865
/// <summary>
866
/// Run a transformation driven by an xml-stylesheet processing instruction in the source document
867
/// </summary>
868

    
869
public class XsltProcessingInstruction : Example {
870

    
871
    public override string testName {
872
        get { return "XsltProcessingInstruction"; }
873
    }
874

    
875
    /// <summary>
876
    /// Run a transformation driven by an xml-stylesheet processing instruction in the source document
877
    /// </summary>
878
    /// <param name="fileNames">
879
    /// 1. The source document
880
    /// </param>
881

    
882
    public override void run(Uri samplesDir)
883
    {
884
        // Create a Processor instance.
885
        Processor processor = new Processor();
886
        XsltExecutable exec;
887

    
888
        // Load the source document
889
        XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/books.xml"));
890
        //Console.WriteLine("=============== source document ===============");
891
        //Console.WriteLine(input.OuterXml);
892
        //Console.WriteLine("=========== end of source document ============");
893

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

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

    
900
        XPathSelector eval = processor.NewXPathCompiler().Compile(path).Load();
901
        eval.ContextItem = input;
902
        XdmAtomicValue hrefval = (XdmAtomicValue)eval.EvaluateSingle();
903
        String href = (hrefval == null ? null : hrefval.ToString());
904

    
905
        if (href == null || href == "")
906
        {
907
            Console.WriteLine("No suitable xml-stylesheet processing instruction found");
908
            return;
909

    
910
        }
911
        else if (href[0] == '#')
912
        {
913

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

    
916
            Console.WriteLine("Locating embedded stylesheet with href = " + href);
917
            String idpath = "id('" + href.Substring(1) + "')";
918
            eval = processor.NewXPathCompiler().Compile(idpath).Load();
919
            eval.ContextItem = input;
920
            XdmNode node = (XdmNode)eval.EvaluateSingle();
921
            if (node == null)
922
            {
923
                Console.WriteLine("No element found with ID " + href.Substring(1));
924
                return;
925
            }
926
            exec = processor.NewXsltCompiler().Compile(node);
927

    
928
        }
929
        else
930
        {
931

    
932
            // The stylesheet is in an external document
933

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

    
936
            // Fetch and compile the referenced stylesheet
937
            exec = processor.NewXsltCompiler().Compile(new Uri(input.BaseUri, href.ToString()));
938
        }
939

    
940
        // Create a transformer 
941
        XsltTransformer transformer = exec.Load();
942

    
943
        // Run it       
944
        transformer.InitialContextNode = input;
945
        XdmDestination results = new XdmDestination();
946
        transformer.Run(results);
947
        Console.WriteLine("1: " + results.XdmNode.OuterXml);
948

    
949
    }
950
}
951

    
952
/// <summary>
953
/// Run an XSLT transformation setting serialization properties from the calling application
954
/// </summary>
955

    
956
public class XsltSettingOutputProperties : Example
957
{
958

    
959
    public override string testName {
960
        get { return "XsltSettingOutputProperties"; }
961
    }
962

    
963
    /// <summary>
964
    /// Run an XSLT transformation setting serialization properties from the calling application
965
    /// </summary>
966

    
967
    public override void run(Uri samplesDir)
968
    {
969
        // Create a Processor instance.
970
        Processor processor = new Processor();
971

    
972
        // Load the source document
973
        XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/books.xml"));
974

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

    
978
        // Set the root node of the source document to be the initial context node
979
        transformer.InitialContextNode = input;
980

    
981
        // Create a serializer, with output to the standard output stream
982
        Serializer serializer = new Serializer();
983
        serializer.SetOutputProperty(Serializer.METHOD, "xml");
984
        serializer.SetOutputProperty(Serializer.INDENT, "no");
985
        serializer.SetOutputWriter(Console.Out);
986

    
987
        // Transform the source XML and serialize the result document
988
        transformer.Run(serializer);
989
    }
990

    
991
}
992

    
993
/// <summary>
994
/// Run an XSLT transformation making use of an XmlResolver to resolve URIs at document build time, at stylesheet compile time 
995
/// and at transformation run-time
996
/// </summary>
997

    
998
public class XsltUsingSourceResolver : Example {
999

    
1000
    public override string testName {
1001
        get { return "XsltUsingSourceResolver"; }
1002
    }
1003

    
1004
    /// <summary>
1005
    /// Run an XSLT transformation making use of an XmlResolver to resolve URIs both at compile time and at run-time
1006
    /// </summary>
1007

    
1008
    public override void run(Uri samplesDir)
1009
    {
1010

    
1011
        // Create a Processor instance.
1012
        Processor processor = new Processor();
1013

    
1014
        // Load the source document
1015
        DocumentBuilder builder = processor.NewDocumentBuilder();
1016
        UserXmlResolver buildTimeResolver = new UserXmlResolver();
1017
        buildTimeResolver.Message = "** Calling build-time XmlResolver: ";
1018
        builder.XmlResolver = buildTimeResolver;
1019
        builder.BaseUri = samplesDir;
1020

    
1021
        String doc = "<!DOCTYPE doc [<!ENTITY e SYSTEM 'flamingo.txt'>]><doc>&e;</doc>";
1022
        MemoryStream ms = new MemoryStream();
1023
        StreamWriter tw = new StreamWriter(ms);
1024
        tw.Write(doc);
1025
        tw.Flush();
1026
        Stream instr = new MemoryStream(ms.GetBuffer(), 0, (int)ms.Length);
1027
        XdmNode input = builder.Build(instr);
1028

    
1029
        // Create a transformer for the stylesheet.
1030
        String stylesheet =
1031
            "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0'>" +
1032
            "<xsl:import href='empty.xslt'/>" +
1033
            "<xsl:template match='/'>" +
1034
            "<out note=\"{doc('heron.txt')}\" ><xsl:copy-of select='.'/></out>" +
1035
            "</xsl:template>" +
1036
            "</xsl:stylesheet>";
1037
 
1038
        XsltCompiler compiler = processor.NewXsltCompiler();
1039
        UserXmlResolver compileTimeResolver = new UserXmlResolver();
1040
        compileTimeResolver.Message = "** Calling compile-time XmlResolver: ";
1041
        compiler.XmlResolver = compileTimeResolver;
1042
        compiler.BaseUri = samplesDir;
1043
        XsltTransformer transformer = compiler.Compile(new XmlTextReader(new StringReader(stylesheet))).Load();
1044

    
1045
        // Set the root node of the source document to be the initial context node
1046
        transformer.InitialContextNode = input;
1047

    
1048
        // Set the user-written XmlResolver
1049
        UserXmlResolver runTimeResolver = new UserXmlResolver();
1050
        runTimeResolver.Message = "** Calling transformation-time XmlResolver: ";
1051
        transformer.InputXmlResolver = runTimeResolver;
1052

    
1053
        // Create a serializer
1054
        Serializer serializer = new Serializer();
1055
        serializer.SetOutputWriter(Console.Out);
1056

    
1057
        // Transform the source XML to System.out.
1058
        transformer.Run(serializer);
1059

    
1060
    }
1061
}
1062

    
1063
/// <summary>
1064
/// Run an XSLT transformation displaying compile-time errors to the console
1065
/// </summary>
1066

    
1067
public class XsltDisplayingErrors : Example {
1068

    
1069
    public override string testName {
1070
        get { return "XsltDisplayingErrors"; }
1071
    }
1072

    
1073
    /// <summary>
1074
    /// Run an XSLT transformation displaying compile-time errors to the console
1075
    /// </summary>
1076

    
1077
    public override void run(Uri samplesDir)
1078
    {
1079
        // Create a Processor instance.
1080
        Processor processor = new Processor();
1081

    
1082
        // Create the XSLT Compiler
1083
        XsltCompiler compiler = processor.NewXsltCompiler();
1084

    
1085

    
1086
        // Define a stylesheet containing errors
1087
        String stylesheet =
1088
            "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0'>\n" +
1089
            "<xsl:template name='eee:template'>\n" +
1090
            "  <xsl:value-of select='32'/>\n" +
1091
            "</xsl:template>\n" +
1092
            "<xsl:template name='main'>\n" +
1093
            "  <xsl:value-of select='$var'/>\n" +
1094
            "</xsl:template>\n" +
1095
            "</xsl:stylesheet>";
1096

    
1097

    
1098
        // Attempt to compile the stylesheet and display the errors
1099
        try
1100
        {
1101
            compiler.BaseUri = new Uri("http://localhost/stylesheet");
1102
            compiler.Compile(new XmlTextReader(new StringReader(stylesheet)));
1103
            Console.WriteLine("Stylesheet compilation succeeded");
1104
        }
1105
        catch (Exception)
1106
        {
1107
            Console.WriteLine("Stylesheet compilation failed");
1108
        }
1109

    
1110

    
1111
    }
1112
}
1113

    
1114
/// <summary>
1115
/// Run an XSLT transformation capturing compile-time errors within the application
1116
/// </summary>
1117

    
1118
public class XsltCapturingErrors : Example
1119
{
1120

    
1121
    public override string testName
1122
    {
1123
        get { return "XsltCapturingErrors"; }
1124
    }
1125

    
1126
    /// <summary>
1127
    /// Run an XSLT transformation capturing compile-time errors within the application
1128
    /// </summary>
1129

    
1130
    public override void run(Uri samplesDir)
1131
    {
1132
        // Create a Processor instance.
1133
        Processor processor = new Processor();
1134
        
1135
        // Create the XSLT Compiler
1136
        XsltCompiler compiler = processor.NewXsltCompiler();
1137

    
1138
        // Create a list to hold the error information
1139
        compiler.ErrorList = new ArrayList();
1140

    
1141
        // Define a stylesheet containing errors
1142
        String stylesheet =
1143
            "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0'>\n" +
1144
            "<xsl:template name='fff:template'>\n" +
1145
            "  <xsl:value-of select='32'/>\n" +
1146
            "</xsl:template>\n" +
1147
            "<xsl:template name='main'>\n" +
1148
            "  <xsl:value-of select='$var'/>\n" +
1149
            "</xsl:template>\n" +
1150
            "</xsl:stylesheet>";
1151

    
1152

    
1153
        // Attempt to compile the stylesheet and display the errors
1154
        try
1155
        {
1156
            compiler.BaseUri = new Uri("http://localhost/stylesheet");
1157
            compiler.Compile(new StringReader(stylesheet));
1158
            Console.WriteLine("Stylesheet compilation succeeded");
1159
        }
1160
        catch (Exception)
1161
        {
1162
            Console.WriteLine("Stylesheet compilation failed with " + compiler.ErrorList.Count + " errors");
1163
            foreach (StaticError error in compiler.ErrorList)
1164
            {
1165
                Console.WriteLine("At line " + error.LineNumber + ": " + error.Message);
1166
            }
1167
        }
1168
    }
1169
}
1170

    
1171
/// <summary>
1172
/// Run an XSLT transformation capturing run-time messages within the application
1173
/// </summary>
1174

    
1175
public class XsltCapturingMessages : Example
1176
{
1177

    
1178
    public override string testName
1179
    {
1180
        get { return "XsltCapturingMessages"; }
1181
    }
1182

    
1183
    /// <summary>
1184
    /// Run an XSLT transformation capturing run-time messages within the application
1185
    /// </summary>
1186

    
1187
    public override void run(Uri samplesDir)
1188
    {
1189

    
1190
        // Create a Processor instance.
1191
        Processor processor = new Processor();
1192

    
1193
        // Create the XSLT Compiler
1194
        XsltCompiler compiler = processor.NewXsltCompiler();
1195

    
1196
        // Define a stylesheet that generates messages
1197
        String stylesheet =
1198
            "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0'>\n" +
1199
            "<xsl:template name='main'>\n" +
1200
            "  <xsl:message><a>starting</a></xsl:message>\n" +
1201
            "  <out><xsl:value-of select='current-date()'/></out>\n" +
1202
            "  <xsl:message><a>finishing</a></xsl:message>\n" +
1203
            "</xsl:template>\n" +
1204
            "</xsl:stylesheet>";
1205

    
1206
        compiler.BaseUri = new Uri("http://localhost/stylesheet");
1207
        XsltExecutable exec = compiler.Compile(new StringReader(stylesheet));
1208

    
1209

    
1210
        // Create a transformer for the stylesheet.
1211
        XsltTransformer transformer = exec.Load();
1212

    
1213
        // Set the name of the initial template
1214
        transformer.InitialTemplate = new QName("", "main");
1215

    
1216
        // Create a Listener to which messages will be written
1217
        transformer.MessageListener = new UserMessageListener();
1218

    
1219
        // Create a serializer
1220
        Serializer serializer = new Serializer();
1221
        serializer.SetOutputWriter(Console.Out);
1222

    
1223
        // Transform the source XML to System.out.
1224
        transformer.Run(serializer);
1225
    }
1226

    
1227
}
1228

    
1229
///
1230
/// Example user-written message listener
1231
///
1232

    
1233
public class UserMessageListener : IMessageListener
1234
{
1235

    
1236
    public void Message(XdmNode content, bool terminate, IXmlLocation location)
1237
    {
1238
        Console.Out.WriteLine("MESSAGE terminate=" + (terminate ? "yes" : "no") + " at " + DateTime.Now);
1239
        Console.Out.WriteLine("From instruction at line " + location.LineNumber +
1240
                " of " + location.BaseUri);
1241
        Console.Out.WriteLine(">>" + content.StringValue);
1242
    }
1243
}
1244

    
1245
/// <summary>
1246
/// Run an XSLT transformation showing source line numbers
1247
/// </summary>
1248

    
1249
public class XsltShowingLineNumbers : Example
1250
{
1251

    
1252
    public override string testName
1253
    {
1254
        get { return "XsltShowingLineNumbers"; }
1255
    }
1256

    
1257
    /// <summary>
1258
    /// Run an XSLT transformation capturing run-time messages within the application
1259
    /// </summary>
1260

    
1261
    public override void run(Uri samplesDir)
1262
    {
1263

    
1264
        // Create a Processor instance.
1265
        Processor processor = new Processor();
1266

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

    
1270
        // Load the source document
1271
        DocumentBuilder builder = processor.NewDocumentBuilder();
1272
        builder.IsLineNumbering = true;
1273
        XdmNode input = builder.Build(new Uri(samplesDir, "data/othello.xml"));
1274

    
1275
        // Create the XSLT Compiler
1276
        XsltCompiler compiler = processor.NewXsltCompiler();
1277

    
1278
        // Define a stylesheet that shows line numbers of source elements
1279
        String stylesheet =
1280
            "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0' xmlns:saxon='http://saxon.sf.net/'>\n" +
1281
            "<xsl:template match='/'>\n" +
1282
            "<out>\n" +
1283
            "  <xsl:for-each select='//ACT'>\n" +
1284
            "  <out><xsl:value-of select='saxon:line-number(.)'/></out>\n" +
1285
            "  </xsl:for-each>\n" +
1286
            "</out>\n" +
1287
            "</xsl:template>\n" +
1288
            "</xsl:stylesheet>";
1289

    
1290
        compiler.BaseUri = new Uri("http://localhost/stylesheet");
1291
        XsltExecutable exec = compiler.Compile(new StringReader(stylesheet));
1292

    
1293

    
1294
        // Create a transformer for the stylesheet.
1295
        XsltTransformer transformer = exec.Load();
1296

    
1297
        // Set the root node of the source document to be the initial context node
1298
        transformer.InitialContextNode = input;
1299

    
1300
        // Create a serializer
1301
        Serializer serializer = new Serializer();
1302
        serializer.SetOutputWriter(Console.Out);
1303

    
1304
        // Transform the source XML to System.out.
1305
        transformer.Run(serializer);
1306
    }
1307

    
1308
}
1309

    
1310
/// <summary>
1311
/// Run an XSLT transformation producing multiple output documents
1312
/// </summary>
1313

    
1314
public class XsltMultipleOutput : Example
1315
{
1316

    
1317
    public override string testName
1318
    {
1319
        get { return "XsltMultipleOutput"; }
1320
    }
1321

    
1322
    /// <summary>
1323
    /// Run an XSLT transformation producing multiple output documents
1324
    /// </summary>
1325

    
1326
    public override void run(Uri samplesDir)
1327
    {
1328
        // Create a Processor instance.
1329
        Processor processor = new Processor();
1330
        processor.SetProperty("http://saxon.sf.net/feature/timing", "true");
1331

    
1332
        // Load the source document
1333
        XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/othello.xml"));
1334

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

    
1338
        // Set the root node of the source document to be the initial context node
1339
        transformer.InitialContextNode = input;
1340
        
1341
        // Set the required stylesheet parameter
1342
        transformer.SetParameter(new QName("", "", "dir"), new XdmAtomicValue(samplesDir.ToString() + "play"));
1343

    
1344
        // Create a serializer
1345
        Serializer serializer = new Serializer();
1346
        serializer.SetOutputWriter(Console.Out);
1347

    
1348
        // Transform the source XML to System.out.
1349
        transformer.Run(serializer);
1350
 
1351
    }
1352

    
1353
}
1354

    
1355

    
1356
/// <summary>
1357
/// Run an XSLT transformation using the id() function, with DTD validation
1358
/// </summary>
1359

    
1360
public class XsltUsingIdFunction : Example
1361
{
1362

    
1363
    public override string testName
1364
    {
1365
        get { return "XsltUsingIdFunction"; }
1366
    }
1367

    
1368
    /// <summary>
1369
    /// Run an XSLT transformation using the id() function, with DTD validation
1370
    /// </summary>
1371

    
1372
    public override void run(Uri samplesDir)
1373
    {
1374
        // Create a Processor instance
1375
        Processor processor = new Processor();
1376

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

    
1381
        String doc = "<!DOCTYPE table [" +
1382
            "<!ELEMENT table (row*)>" +
1383
            "<!ELEMENT row EMPTY>" +
1384
            "<!ATTLIST row xml:id ID #REQUIRED>" +
1385
            "<!ATTLIST row value CDATA #REQUIRED>]>" +
1386
            "<table><row xml:id='A123' value='green'/><row xml:id='Z789' value='blue'/></table>";
1387
         
1388
        DocumentBuilder builder = processor.NewDocumentBuilder();
1389
        builder.DtdValidation = true;
1390
        builder.BaseUri = samplesDir;
1391
        MemoryStream ms = new MemoryStream();
1392
        StreamWriter tw = new StreamWriter(ms);
1393
        tw.Write(doc);
1394
        tw.Flush();
1395
        Stream instr = new MemoryStream(ms.GetBuffer(), 0, (int)ms.Length);
1396
        XdmNode input = builder.Build(instr);
1397

    
1398
        // Define a stylesheet that uses the id() function
1399
        String stylesheet =
1400
            "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0'>\n" +
1401
            "<xsl:template match='/'>\n" +
1402
            "  <xsl:copy-of select=\"id('Z789')\"/>\n" +
1403
            "</xsl:template>\n" +
1404
            "</xsl:stylesheet>";
1405

    
1406
        XsltCompiler compiler = processor.NewXsltCompiler();
1407
        compiler.BaseUri = new Uri("http://localhost/stylesheet");
1408
        XsltExecutable exec = compiler.Compile(new StringReader(stylesheet));
1409

    
1410
        //Create a transformer for the stylesheet
1411
        XsltTransformer transformer = exec.Load();
1412

    
1413
        // Set the root node of the source document to be the initial context node
1414
        transformer.InitialContextNode = input;
1415

    
1416
        //Set the destination
1417
        XdmDestination results = new XdmDestination();
1418

    
1419
        // Transform the XML
1420
        transformer.Run(results);
1421

    
1422
        // Show the result
1423
        Console.WriteLine(results.XdmNode.ToString());
1424

    
1425
    }
1426

    
1427
}
1428

    
1429
/// <summary>
1430
/// Show a transformation using a user-written result document handler. This example
1431
/// captures each of the result documents in a DOM, and creates a Hashtable that indexes
1432
/// the DOM trees according to their absolute URI. On completion, it writes all the DOMs
1433
/// to the standard output.
1434
/// </summary>
1435
    
1436
public class XsltUsingResultHandler : Example
1437
{
1438

    
1439
    public override string testName
1440
    {
1441
        get { return "XsltUsingResultHandler"; }
1442
    }
1443

    
1444
    /// <summary>
1445
    /// Show a transformation using a user-written result document handler. This example
1446
    /// captures each of the result documents in a DOM, and creates a Hashtable that indexes
1447
    /// the DOM trees according to their absolute URI. On completion, it writes all the DOMs
1448
    /// to the standard output.
1449
    /// </summary>
1450

    
1451
    public override void run(Uri samplesDir)
1452
    {
1453
        // Create a Processor instance.
1454
        Processor processor = new Processor();
1455

    
1456
        // Load the source document
1457
        XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/othello.xml"));
1458

    
1459
        // Define a stylesheet that splits the document up
1460
        String stylesheet =
1461
            "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0'>\n" +
1462
            "<xsl:template match='/'>\n" +
1463
            "  <xsl:for-each select='//ACT'>\n" +
1464
            "    <xsl:result-document href='{position()}.xml'>\n" +
1465
            "      <xsl:copy-of select='TITLE'/>\n" +
1466
            "    </xsl:result-document>\n" +
1467
            "  </xsl:for-each>\n" +
1468
            "</xsl:template>\n" +
1469
            "</xsl:stylesheet>";
1470

    
1471
        XsltCompiler compiler = processor.NewXsltCompiler();
1472
        compiler.BaseUri = new Uri("http://localhost/stylesheet");
1473
        XsltExecutable exec = compiler.Compile(new StringReader(stylesheet));
1474
        
1475
        // Create a transformer for the stylesheet.
1476
        XsltTransformer transformer = exec.Load();
1477

    
1478
        // Set the root node of the source document to be the initial context node
1479
        transformer.InitialContextNode = input;
1480

    
1481
        // Establish the result document handler
1482
        Hashtable results = new Hashtable();
1483
        transformer.ResultDocumentHandler = new UserResultDocumentHandler(results);
1484

    
1485
        // Transform the source XML to a NullDestination (because we only want the secondary result files).
1486
        transformer.Run(new NullDestination());
1487

    
1488
        // Process the captured DOM results
1489
        foreach (DictionaryEntry entry in results)
1490
        {
1491
            string uri = (string)entry.Key;
1492
            Console.WriteLine("\nResult File " + uri);
1493
            DomDestination dom = (DomDestination)results[uri];
1494
            Console.Write(dom.XmlDocument.OuterXml);
1495
        }
1496

    
1497
    }
1498

    
1499
}
1500

    
1501
/// <summary>
1502
/// Show a transformation using a registered collection
1503
/// </summary>
1504

    
1505
public class XsltUsingRegisteredCollection : Example
1506
{
1507

    
1508
    public override string testName
1509
    {
1510
        get { return "XsltUsingRegisteredCollection"; }
1511
    }
1512

    
1513
    /// <summary>
1514
    /// Show a transformation using a registered collection
1515
    /// </summary>
1516

    
1517
    public override void run(Uri samplesDir)
1518
    {
1519
        // Create a Processor instance.
1520
        Processor processor = new Processor();
1521

    
1522
        // Load the source document
1523
        XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/othello.xml"));
1524

    
1525
        // Define a stylesheet that splits the document up
1526
        String stylesheet =
1527
            "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0'>\n" +
1528
            "<xsl:template name='main'>\n" +
1529
            " <out>\n" +
1530
            "  <xsl:for-each select=\"collection('http://www.example.org/my-collection')\">\n" +
1531
            "    <document uri='{document-uri(.)}' nodes='{count(//*)}'/>\n" +
1532
            "  </xsl:for-each><zzz/>\n" +
1533
            "  <xsl:for-each select=\"collection('http://www.example.org/my-collection')\">\n" +
1534
            "    <document uri='{document-uri(.)}' nodes='{count(//*)}'/>\n" +
1535
            "  </xsl:for-each>\n" +
1536
            " </out>\n" +
1537
            "</xsl:template>\n" +
1538
            "</xsl:stylesheet>";
1539

    
1540
        Uri[] documentList = new Uri[2];
1541
        documentList[0] = new Uri(samplesDir, "data/othello.xml");
1542
        documentList[1] = new Uri(samplesDir, "data/books.xml");
1543
        processor.RegisterCollection(new Uri("http://www.example.org/my-collection"), documentList);
1544

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

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

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

    
1555
        //Set the destination
1556
        XdmDestination results = new XdmDestination();
1557

    
1558
        // Transform the XML
1559
        transformer.Run(results);
1560

    
1561
        // Show the result
1562
        Console.WriteLine(results.XdmNode.ToString());
1563

    
1564
    }
1565
}
1566

    
1567
/// <summary>
1568
/// Show a transformation using a registered collection
1569
/// </summary>
1570

    
1571
public class XsltUsingDirectoryCollection : Example
1572
{
1573

    
1574
    public override string testName
1575
    {
1576
        get { return "XsltUsingDirectoryCollection"; }
1577
    }
1578

    
1579
    /// <summary>
1580
    /// Show a transformation using a collection that maps to a directory
1581
    /// </summary>
1582

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

    
1588
        // Load the source document
1589
        XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/othello.xml"));
1590

    
1591
        // Define a stylesheet that splits the document up
1592
        String stylesheet =
1593
            "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0'>\n" +
1594
            "<xsl:template name='main'>\n" +
1595
            " <out>\n" +
1596
            "  <xsl:for-each select=\"collection('" + samplesDir + "?recurse=yes;select=*.xml;on-error=warning')\">\n" +
1597
            "    <document uri='{document-uri(.)}' nodes='{count(//*)}'/>\n" +
1598
            "  </xsl:for-each><zzz/>\n" +
1599
            " </out>\n" +
1600
            "</xsl:template>\n" +
1601
            "</xsl:stylesheet>";
1602

    
1603
       
1604
        XsltCompiler compiler = processor.NewXsltCompiler();
1605
        compiler.BaseUri = new Uri("http://localhost/stylesheet");
1606
        XsltExecutable exec = compiler.Compile(new StringReader(stylesheet));
1607

    
1608
        // Create a transformer for the stylesheet.
1609
        XsltTransformer transformer = exec.Load();
1610

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

    
1614
        //Set the destination
1615
        XdmDestination results = new XdmDestination();
1616

    
1617
        // Transform the XML
1618
        transformer.Run(results);
1619

    
1620
        // Show the result
1621
        Console.WriteLine(results.XdmNode.ToString());
1622

    
1623
    }
1624

    
1625
}
1626

    
1627
/// <summary>
1628
/// Show a transformation using calls to extension functions
1629
/// </summary>
1630

    
1631
public class XsltExtensibility : Example
1632
{
1633

    
1634
    public override string testName
1635
    {
1636
        get { return "XsltExtensibility"; }
1637
    }
1638

    
1639
    /// <summary>
1640
    /// Show a transformation using calls to extension functions
1641
    /// </summary>
1642

    
1643
    public override void run(Uri samplesDir)
1644
    {
1645

    
1646
        // Create a Processor instance.
1647
        Processor processor = new Processor();
1648

    
1649
        // Identify the Processor version
1650
        Console.WriteLine(processor.ProductVersion);
1651

    
1652
        // Set diagnostics
1653
        //processor.SetProperty("http://saxon.sf.net/feature/trace-external-functions", "true");
1654

    
1655
        // Create the stylesheet
1656
        String s = @"<xsl:transform version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'" +
1657
            @" xmlns:ext='clitype:SampleExtensions.SampleExtensions?asm=SampleExtensions' " +
1658
            @" xmlns:tz='clitype:System.TimeZone' " +
1659
            @" xmlns:math='http://example.math.co.uk/demo' " +
1660
            @" xmlns:env='http://example.env.co.uk/demo' " +
1661
            @" exclude-result-prefixes='ext math env tz'> " +
1662
            @" <xsl:param name='timezone' required='yes'/> " +
1663
            @" <xsl:template match='/'> " +
1664
            @" <out addition='{ext:add(2,2)}' " +
1665
            @" average='{ext:average((1,2,3,4,5,6))}' " +
1666
            @" firstchild='{ext:nameOfFirstChild(.)}' " +
1667
            @" timezone='{tz:StandardName($timezone)}' " +
1668
            @" sqrt2='{math:sqrt(2.0e0)}' " +
1669
            @" defaultNamespace='{env:defaultNamespace()}' " +
1670
            @" sqrtEmpty='{math:sqrt(())}'> " +
1671
            @" <xsl:copy-of select='ext:FirstChild((//ITEM)[1])'/> " +
1672
            @" <defaultNS value='{env:defaultNamespace()}' xsl:xpath-default-namespace='http://default.namespace.com/' /> " +
1673
            @" <combine1><xsl:sequence select='ext:combine(ext:FirstChild((//ITEM)[1]), count(*))'/></combine1> " +
1674
            @" <combine2><xsl:sequence select='ext:combine((//TITLE)[1], (//AUTHOR)[1])'/></combine2> " +
1675
            @" </out> " +
1676
            @" </xsl:template></xsl:transform>";
1677

    
1678
        // Register the integrated extension functions math:sqrt and env:defaultNamespace
1679

    
1680
        processor.RegisterExtensionFunction(new Sqrt());
1681
        processor.RegisterExtensionFunction(new DefaultNamespace());
1682

    
1683
        // Create a transformer for the stylesheet.
1684
        XsltTransformer transformer = processor.NewXsltCompiler().Compile(new StringReader(s)).Load();
1685

    
1686
        // Load the source document (must be a wrapper around an XmlDocument for this test)
1687
        XmlDocument doc = new XmlDocument();
1688
        doc.Load(new XmlTextReader(samplesDir.AbsolutePath + "data/books.xml"));
1689
        XdmNode input = processor.NewDocumentBuilder().Wrap(doc);
1690

    
1691
        // Set the root node of the source document to be the initial context node
1692
        transformer.InitialContextNode = input;
1693

    
1694
        // Supply a parameter
1695
        transformer.SetParameter(new QName("", "timezone"),
1696
                  XdmAtomicValue.WrapExternalObject(TimeZone.CurrentTimeZone));
1697

    
1698
        // Create a serializer
1699
        Serializer serializer = new Serializer();
1700
        serializer.SetOutputWriter(Console.Out);
1701
        serializer.SetOutputProperty(Serializer.INDENT, "yes");
1702

    
1703
        // Transform the source XML to System.out.
1704
        transformer.Run(serializer);
1705
    }
1706

    
1707
}
1708

    
1709
/// <summary>
1710
/// Show a transformation using calls to extension functions
1711
/// </summary>
1712

    
1713
public class XsltIntegratedExtension : Example
1714
{
1715

    
1716
    public override string testName
1717
    {
1718
        get { return "XsltIntegratedExtension"; }
1719
    }
1720

    
1721
    /// <summary>
1722
    /// Show a transformation using calls to extension functions
1723
    /// </summary>
1724

    
1725
    public override void run(Uri samplesDir)
1726
    {
1727

    
1728
        // Create a Processor instance.
1729
        Processor processor = new Processor();
1730

    
1731
        // Identify the Processor version
1732
        Console.WriteLine(processor.ProductVersion);
1733

    
1734
        // Set diagnostics
1735
        //processor.SetProperty("http://saxon.sf.net/feature/trace-external-functions", "true");
1736

    
1737
        // Create the stylesheet
1738
        String s = @"<xsl:transform version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'" +
1739
            @" xmlns:math='http://example.math.co.uk/demo'> " +
1740
            @" <xsl:template name='go'> " +
1741
            @" <out sqrt2='{math:sqrt(2.0e0)}' " +
1742
            @" sqrtEmpty='{math:sqrt(())}'/> " +
1743
            @" </xsl:template></xsl:transform>";
1744

    
1745
        // Register the integrated extension function math:sqrt
1746

    
1747
        processor.RegisterExtensionFunction(new Sqrt());
1748

    
1749
        // Create a transformer for the stylesheet.
1750
        XsltTransformer transformer = processor.NewXsltCompiler().Compile(new StringReader(s)).Load();
1751

    
1752
        // Set the root node of the source document to be the initial context node
1753
        transformer.InitialTemplate = new QName("go");
1754

    
1755
        // Create a serializer
1756
        Serializer serializer = new Serializer();
1757
        serializer.SetOutputWriter(Console.Out);
1758
        serializer.SetOutputProperty(Serializer.INDENT, "yes");
1759

    
1760
        // Transform the source XML to System.out.
1761
        transformer.Run(serializer);
1762
    }
1763

    
1764
}
1765

    
1766
/// <summary>
1767
/// Example extension function to compute a square root.
1768
/// </summary>
1769

    
1770
public class Sqrt : ExtensionFunctionDefinition
1771
{
1772
    public override QName FunctionName
1773
    {
1774
        get
1775
        {
1776
            return new QName("http://example.math.co.uk/demo", "sqrt");
1777
        }
1778
    }
1779

    
1780
    public override int MinimumNumberOfArguments
1781
    {
1782
        get
1783
        {
1784
            return 1;
1785
        }
1786
    }
1787

    
1788
    public override int MaximumNumberOfArguments
1789
    {
1790
        get
1791
        {
1792
            return 1;
1793
        }
1794
    }
1795

    
1796
    public override XdmSequenceType[] ArgumentTypes
1797
    {
1798
        get
1799
        {
1800
            return new XdmSequenceType[]{
1801
                    new XdmSequenceType(XdmAtomicType.BuiltInAtomicType(QName.XS_DOUBLE), '?')
1802
                };
1803
        }
1804
    }
1805

    
1806
    public override XdmSequenceType ResultType(XdmSequenceType[] ArgumentTypes)
1807
    {
1808
        return new XdmSequenceType(XdmAtomicType.BuiltInAtomicType(QName.XS_DOUBLE), '?');
1809
    }
1810

    
1811
    public override bool TrustResultType
1812
    {
1813
        get
1814
        {
1815
            return true;
1816
        }
1817
    }
1818

    
1819

    
1820
    public override ExtensionFunctionCall MakeFunctionCall()
1821
    {
1822
        return new SqrtCall();
1823
    }
1824
}
1825

    
1826
internal class SqrtCall : ExtensionFunctionCall
1827
{
1828
    public override IXdmEnumerator Call(IXdmEnumerator[] arguments, DynamicContext context)
1829
    {
1830
        Boolean exists = arguments[0].MoveNext();
1831
        if (exists)
1832
        {
1833
            XdmAtomicValue arg = (XdmAtomicValue)arguments[0].Current;
1834
            double val = (double)arg.Value;
1835
            double sqrt = System.Math.Sqrt(val);
1836
            XdmAtomicValue result = new XdmAtomicValue(sqrt);
1837
            return (IXdmEnumerator)result.GetEnumerator();
1838
        }
1839
        else
1840
        {
1841
            return EmptyEnumerator.INSTANCE;
1842
        }
1843
    }
1844

    
1845
}
1846

    
1847
/// <summary>
1848
/// Example extension function to return the default namespace from the static context
1849
/// </summary>
1850

    
1851
public class DefaultNamespace : ExtensionFunctionDefinition
1852
{
1853
    public override QName FunctionName
1854
    {
1855
        get
1856
        {
1857
            return new QName("http://example.env.co.uk/demo", "defaultNamespace");
1858
        }
1859
    }
1860

    
1861
    public override int MinimumNumberOfArguments
1862
    {
1863
        get
1864
        {
1865
            return 0;
1866
        }
1867
    }
1868

    
1869
    public override int MaximumNumberOfArguments
1870
    {
1871
        get
1872
        {
1873
            return 0;
1874
        }
1875
    }
1876

    
1877
    public override XdmSequenceType[] ArgumentTypes
1878
    {
1879
        get
1880
        {
1881
            return new XdmSequenceType[]{};
1882
        }
1883
    }
1884

    
1885
    public override bool DependsOnFocus
1886
    {
1887
        get
1888
        {
1889
            return true;
1890
            // actually it depends on the static context rather than the focus; but returning true is necessary
1891
            // to avoid the call being extracted to a global variable.
1892
        }
1893
    }
1894

    
1895
    public override XdmSequenceType ResultType(XdmSequenceType[] ArgumentTypes)
1896
    {
1897
        return new XdmSequenceType(XdmAtomicType.BuiltInAtomicType(QName.XS_STRING), '?');
1898
    }
1899

    
1900
    public override bool TrustResultType
1901
    {
1902
        get
1903
        {
1904
            return true;
1905
        }
1906
    }
1907

    
1908

    
1909
    public override ExtensionFunctionCall MakeFunctionCall()
1910
    {
1911
        return new DefaultNamespaceCall();
1912
    }
1913
}
1914

    
1915
internal class DefaultNamespaceCall : ExtensionFunctionCall
1916
{
1917
    private string defaultNamespace;
1918

    
1919
    public override void SupplyStaticContext(StaticContext context)
1920
    {
1921
        defaultNamespace = context.GetNamespaceForPrefix("");
1922
    }
1923
    
1924
    public override IXdmEnumerator Call(IXdmEnumerator[] arguments, DynamicContext context)
1925
    {
1926
        if (defaultNamespace != null)
1927
        {
1928
            return (IXdmEnumerator)new XdmAtomicValue(defaultNamespace).GetEnumerator();
1929
        }
1930
        else
1931
        {
1932
            return EmptyEnumerator.INSTANCE;
1933
        }
1934
    }
1935

    
1936
}
1937

    
1938
/// <summary>
1939
/// Show a query producing a document as its result and serializing this to a FileStream
1940
/// </summary>
1941

    
1942
public class XQueryToStream : Example
1943
{
1944

    
1945
    public override string testName
1946
    {
1947
        get { return "XQueryToStream"; }
1948
    }
1949

    
1950
    /// <summary>
1951
    /// Show a query producing a document as its result and serializing this to a FileStream
1952
    /// </summary>
1953

    
1954
    public override void run(Uri samplesDir)
1955
    {
1956
        Processor processor = new Processor();
1957
        XQueryCompiler compiler = processor.NewXQueryCompiler();
1958
        compiler.BaseUri = samplesDir.ToString();
1959
        compiler.DeclareNamespace("saxon", "http://saxon.sf.net/");
1960
        XQueryExecutable exp = compiler.Compile("<saxon:example>{static-base-uri()}</saxon:example>");
1961
        XQueryEvaluator eval = exp.Load();
1962
        Serializer qout = new Serializer();
1963
        qout.SetOutputProperty(Serializer.METHOD, "xml");
1964
        qout.SetOutputProperty(Serializer.INDENT, "yes");
1965
        qout.SetOutputProperty(Serializer.SAXON_INDENT_SPACES, "1");
1966
        qout.SetOutputStream(new FileStream("testoutput.xml", FileMode.Create, FileAccess.Write));
1967
        Console.WriteLine("Output written to testoutput.xml");
1968
        eval.Run(qout);
1969
    }
1970

    
1971
}
1972

    
1973
/// <summary>
1974
/// Show a query producing a single atomic value as its result and returning the value
1975
/// to the Java application
1976
/// </summary>
1977

    
1978
public class XQueryToAtomicValue : Example
1979
{
1980

    
1981
    public override string testName
1982
    {
1983
        get { return "XQueryToAtomicValue"; }
1984
    }
1985

    
1986
    /// <summary>
1987
    /// Show a query producing a single atomic value as its result and returning the value
1988
    /// to the Java application
1989
    /// </summary>
1990

    
1991
    public override void run(Uri samplesDir)
1992
    {
1993
        Processor processor = new Processor();
1994
        XQueryCompiler compiler = processor.NewXQueryCompiler();
1995
        XQueryExecutable exp = compiler.Compile("avg(for $i in 1 to 10 return $i * $i)");
1996
        XQueryEvaluator eval = exp.Load();
1997
        XdmAtomicValue result = (XdmAtomicValue)eval.EvaluateSingle();
1998
        Console.WriteLine("Result type: " + result.Value.GetType());
1999
        Console.WriteLine("Result value: " + (decimal)result.Value);
2000
    }
2001

    
2002
}
2003

    
2004
/// <summary>
2005
/// Show a query producing a DOM as its input and producing a DOM as its output
2006
/// </summary>
2007

    
2008
public class XQueryToDom : Example
2009
{
2010

    
2011
    public override string testName
2012
    {
2013
        get { return "XQueryToDom"; }
2014
    }
2015

    
2016
    /// <summary>
2017
    /// Show a query producing a DOM as its input and producing a DOM as its output
2018
    /// </summary>
2019

    
2020
    public override void run(Uri samplesDir)
2021
    {
2022
        Processor processor = new Processor();
2023

    
2024
        XmlDocument input = new XmlDocument();
2025
        input.Load(new Uri(samplesDir, "data/books.xml").ToString());
2026
        XdmNode indoc = processor.NewDocumentBuilder().Build(new XmlNodeReader(input));
2027

    
2028
        XQueryCompiler compiler = processor.NewXQueryCompiler();
2029
        XQueryExecutable exp = compiler.Compile("<doc>{reverse(/*/*)}</doc>");
2030
        XQueryEvaluator eval = exp.Load();
2031
        eval.ContextItem = indoc;
2032
        DomDestination qout = new DomDestination();
2033
        eval.Run(qout);
2034
        XmlDocument outdoc = qout.XmlDocument;
2035
        Console.WriteLine(outdoc.OuterXml);  
2036
    }
2037

    
2038
}
2039

    
2040
/// <summary>
2041
/// Show a query producing a Saxon tree as its input and producing a Saxon tree as its output
2042
/// </summary>
2043

    
2044
public class XQueryToXdm : Example
2045
{
2046

    
2047
    public override string testName
2048
    {
2049
        get { return "XQueryToXdm"; }
2050
    }
2051

    
2052
    /// <summary>
2053
    /// Show a query producing a Saxon tree as its input and producing a Saxon tree as its output
2054
    /// </summary>
2055

    
2056
    public override void run(Uri samplesDir)
2057
    {
2058
        Processor processor = new Processor();
2059

    
2060
        DocumentBuilder loader = processor.NewDocumentBuilder();
2061
        loader.BaseUri = new Uri(samplesDir, "data/books.xml");
2062
        XdmNode indoc = loader.Build(loader.BaseUri);
2063

    
2064
        XQueryCompiler compiler = processor.NewXQueryCompiler();
2065
        XQueryExecutable exp = compiler.Compile("<doc>{reverse(/*/*)}</doc>");
2066
        XQueryEvaluator eval = exp.Load();
2067
        eval.ContextItem = indoc;
2068
        XdmDestination qout = new XdmDestination();
2069
        eval.Run(qout);
2070
        XdmNode outdoc = qout.XdmNode;
2071
        Console.WriteLine(outdoc.OuterXml);  
2072
    }
2073

    
2074
}
2075

    
2076
/// <summary>
2077
/// Show a query making a direct call to a user-defined function defined in the query
2078
/// </summary>
2079

    
2080
public class XQueryCallFunction : Example
2081
{
2082

    
2083
    public override string testName
2084
    {
2085
        get { return "XQueryCallFunction"; }
2086
    }
2087

    
2088
    /// <summary>
2089
    /// Show a direct call on a user-defined function defined within the query
2090
    /// </summary>
2091

    
2092
    public override void run(Uri samplesDir)
2093
    {
2094
        Processor processor = new Processor();
2095

    
2096
        XQueryCompiler qc = processor.NewXQueryCompiler();
2097
        XQueryExecutable exp1 = qc.Compile("declare namespace f='f.ns';" +
2098
               "declare variable $z := 1 + xs:integer(doc-available('file:///c:/MyJava/testdata/books.xml'));" +
2099
               "declare variable $p as xs:integer external;" +
2100
               "declare function f:t1($v1 as xs:integer) { " +
2101
               "   $v1 div $z + $p" +
2102
               "};" +
2103
               "10");
2104
        XQueryEvaluator ev = exp1.Load();
2105
        ev.SetExternalVariable(new QName("", "p"), new XdmAtomicValue(39));
2106
        XdmValue v1 = new XdmAtomicValue(10);
2107
        XdmValue result = ev.CallFunction(new QName("f.ns", "f:t1"), new XdmValue[]{v1});
2108
        Console.WriteLine("First result (expected 44): " + result.ToString());
2109
        v1 = new XdmAtomicValue(20);
2110
        result = ev.CallFunction(new QName("f.ns", "f:t1"), new XdmValue[]{v1});
2111
        Console.WriteLine("Second result (expected 49): " + result.ToString());
2112
    }
2113

    
2114
}
2115

    
2116

    
2117

    
2118
/// <summary>
2119
/// Show a query producing a sequence as its result and returning the sequence
2120
/// to the Java application in the form of an iterator. For each item in the
2121
/// result, its string value is output.
2122
/// </summary>
2123

    
2124
public class XQueryToSequence : Example
2125
{
2126

    
2127
    public override string testName
2128
    {
2129
        get { return "XQueryToSequence"; }
2130
    }
2131

    
2132
    /// <summary>
2133
    /// Show a query producing a sequence as its result and returning the sequence
2134
    /// to the Java application in the form of an iterator. For each item in the
2135
    /// result, its string value is output.
2136
    /// </summary>
2137

    
2138
    public override void run(Uri samplesDir)
2139
    {
2140
        Processor processor = new Processor();
2141
        XQueryCompiler compiler = processor.NewXQueryCompiler();
2142
        XQueryExecutable exp = compiler.Compile("for $i in 1 to 10 return $i * $i");
2143
        XQueryEvaluator eval = exp.Load();
2144
        XdmValue value = eval.Evaluate();
2145
        IEnumerator e = value.GetEnumerator();
2146
        while (e.MoveNext()) {
2147
            XdmItem item = (XdmItem)e.Current;
2148
            Console.WriteLine(item.ToString());
2149
        }
2150

    
2151
    }
2152

    
2153
}
2154

    
2155
/// <summary>
2156
/// Show a query reading an input document using an XmlReader (the .NET XML parser)
2157
/// </summary>
2158

    
2159
public class XQueryFromXmlReader : Example
2160
{
2161

    
2162
    public override string testName
2163
    {
2164
        get { return "XQueryFromXmlReader"; }
2165
    }
2166

    
2167
    /// <summary>
2168
    /// Show a query reading an input document using an XmlReader (the .NET XML parser)
2169
    /// </summary>
2170

    
2171
    public override void run(Uri samplesDir)
2172
    {
2173
        Processor processor = new Processor();
2174

    
2175
        String inputFileName = new Uri(samplesDir, "data/books.xml").ToString();
2176
        XmlTextReader reader = new XmlTextReader(inputFileName, 
2177
            UriConnection.getReadableUriStream(new Uri(samplesDir, "data/books.xml")));
2178
            //new FileStream(inputFileName, FileMode.Open, FileAccess.Read));
2179
        reader.Normalization = true;
2180

    
2181
        // add a validating reader - not to perform validation, but to expand entity references
2182
        XmlValidatingReader validator = new XmlValidatingReader(reader);
2183
        validator.ValidationType = ValidationType.None;
2184

    
2185
        XdmNode doc = processor.NewDocumentBuilder().Build(validator);
2186

    
2187
        XQueryCompiler compiler = processor.NewXQueryCompiler();
2188
        XQueryExecutable exp = compiler.Compile("/");
2189
        XQueryEvaluator eval = exp.Load();
2190
        eval.ContextItem = doc;
2191
        Serializer qout = new Serializer();
2192
        qout.SetOutputProperty(Serializer.METHOD, "xml");
2193
        qout.SetOutputProperty(Serializer.INDENT, "yes");
2194
        qout.SetOutputStream(new FileStream("testoutput2.xml", FileMode.Create, FileAccess.Write));
2195
        eval.Run(qout);
2196
    }
2197

    
2198
}
2199

    
2200
/// <summary>
2201
/// Show a query producing a sequence as its result and returning the sequence
2202
/// to the Java application in the form of an iterator. The sequence is then
2203
/// output by serializing each item individually, with each item on a new line.
2204
/// </summary>
2205

    
2206
public class XQueryToSerializedSequence : Example
2207
{
2208

    
2209
    public override string testName
2210
    {
2211
        get { return "XQueryToSerializedSequence"; }
2212
    }
2213

    
2214
    /// <summary>
2215
    /// Show a query producing a sequence as its result and returning the sequence
2216
    /// to the Java application in the form of an iterator. The sequence is then
2217
    /// output by serializing each item individually, with each item on a new line.
2218
    /// </summary>
2219

    
2220
    public override void run(Uri samplesDir)
2221
    {
2222
        Processor processor = new Processor();
2223
        String inputFileName = new Uri(samplesDir, "data/books.xml").ToString();
2224
        //XmlTextReader reader = new XmlTextReader(inputFileName,
2225
        //    new FileStream(inputFileName, FileMode.Open, FileAccess.Read));
2226
        XmlTextReader reader = new XmlTextReader(inputFileName,
2227
            UriConnection.getReadableUriStream(new Uri(samplesDir, "data/books.xml")));
2228
        reader.Normalization = true;
2229

    
2230
        // add a validating reader - not to perform validation, but to expand entity references
2231
        XmlValidatingReader validator = new XmlValidatingReader(reader);
2232
        validator.ValidationType = ValidationType.None;
2233

    
2234
        XdmNode doc = processor.NewDocumentBuilder().Build(reader);
2235

    
2236
        XQueryCompiler compiler = processor.NewXQueryCompiler();
2237
        XQueryExecutable exp = compiler.Compile("//ISBN");
2238
        XQueryEvaluator eval = exp.Load();
2239
        eval.ContextItem = doc;
2240

    
2241
        foreach (XdmNode node in eval) {
2242
            Console.WriteLine(node.OuterXml);
2243
        }        
2244
    }
2245

    
2246
}
2247

    
2248
/// <summary>
2249
/// Show a query that takes a parameter (external variable) as input.
2250
/// The query produces a single atomic value as its result and returns the value
2251
/// to the Java application. 
2252
/// </summary>
2253

    
2254
public class XQueryUsingParameter : Example
2255
{
2256

    
2257
    public override string testName
2258
    {
2259
        get { return "XQueryUsingParameter"; }
2260
    }
2261

    
2262
    /// <summary>
2263
    /// Show a query that takes a parameter (external variable) as input.
2264
    /// The query produces a single atomic value as its result and returns the value
2265
    /// to the Java application. 
2266
    /// </summary>
2267

    
2268
    public override void run(Uri samplesDir)
2269
    {
2270
        Processor processor = new Processor();
2271
        XQueryCompiler compiler = processor.NewXQueryCompiler();
2272
        compiler.DeclareNamespace("p", "http://saxon.sf.net/ns/p");
2273
        XQueryExecutable exp = compiler.Compile(
2274
                "declare variable $p:in as xs:integer external; $p:in * $p:in");
2275
        XQueryEvaluator eval = exp.Load();
2276
        eval.SetExternalVariable(new QName("http://saxon.sf.net/ns/p", "p:in"), new XdmAtomicValue(12));
2277
        XdmAtomicValue result = (XdmAtomicValue)eval.EvaluateSingle();
2278
        Console.WriteLine("Result type: " + result.Value.GetType());
2279
        Console.WriteLine("Result value: " + (long)result.Value);        
2280
    }
2281

    
2282
}
2283

    
2284
/// <summary>
2285
/// Show a query consisting of two modules, using a QueryResolver to resolve
2286
/// the "import module" declaration
2287
/// </summary>
2288

    
2289
public class XQueryMultiModule : Example
2290
{
2291

    
2292
    public override string testName
2293
    {
2294
        get { return "XQueryMultiModule"; }
2295
    }
2296

    
2297
    /// <summary>
2298
    /// Show a query consisting of two modules, using a QueryResolver to resolve
2299
    /// the "import module" declaration
2300
    /// </summary>
2301

    
2302
    public override void run(Uri samplesDir)
2303
    {
2304

    
2305
        String mod1 = "import module namespace m2 = 'http://www.example.com/module2';" +
2306
                      "m2:square(3)";
2307

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

    
2311
        Processor processor = new Processor();
2312
        XQueryCompiler compiler = processor.NewXQueryCompiler();
2313

    
2314
        InlineModuleResolver resolver = new InlineModuleResolver();
2315
        resolver.AddModule(new Uri("http://www.example.com/module2"), mod2);
2316
        compiler.QueryResolver = resolver;
2317
        XQueryExecutable exp = compiler.Compile(mod1);
2318
        XQueryEvaluator eval = exp.Load();
2319

    
2320
        XdmAtomicValue result = (XdmAtomicValue)eval.EvaluateSingle();
2321
        Console.WriteLine("Result type: " + result.Value.GetType());
2322
        Console.WriteLine("Result value: " + (long)result.Value);      
2323
    }
2324

    
2325
    // A simple QueryResolver designed to show that the actual query
2326
    // text can come from anywhere: in this case, the resolver maintains
2327
    // a simple mapping of module URIs onto strings.
2328

    
2329
    public class InlineModuleResolver : IQueryResolver {
2330

    
2331
        private Hashtable modules = new Hashtable();
2332

    
2333
        public void AddModule(Uri moduleName, String moduleText) {
2334
            modules.Add(moduleName, moduleText);
2335
        }
2336

    
2337
        public Uri[] GetModules(String moduleUri, Uri baseUri, String[] locationHints) {
2338
            Uri[] result = { new Uri(moduleUri) };
2339
            return result;
2340
        }
2341

    
2342
        public Object GetEntity(Uri absoluteUri) {
2343
            return modules[absoluteUri];
2344
        }
2345
    }
2346

    
2347
}
2348

    
2349
/// <summary>
2350
/// Demonstrate XQuery extensibility using user-written extension functions
2351
/// </summary>
2352

    
2353
public class XQueryExtensibility : Example
2354
{
2355

    
2356
    public override string testName
2357
    {
2358
        get { return "XQueryExtensibility"; }
2359
    }
2360

    
2361
    /// <summary>
2362
    /// Demonstrate XQuery extensibility using user-written extension functions
2363
    /// </summary>
2364

    
2365
    public override void run(Uri samplesDir)
2366
    {
2367
        String query =
2368
            "declare namespace ext = \"clitype:SampleExtensions.SampleExtensions?asm=SampleExtensions\";" +
2369
            "<out>" +
2370
            "  <addition>{ext:add(2,2)}</addition>" +
2371
            "  <average>{ext:average((1,2,3,4,5,6))}</average>" +
2372
            "  <language>{ext:hostLanguage()}</language>" +
2373
            "</out>";
2374

    
2375
        Processor processor = new Processor();
2376
        XQueryCompiler compiler = processor.NewXQueryCompiler();
2377
        XQueryExecutable exp = compiler.Compile(query);
2378
        XQueryEvaluator eval = exp.Load();
2379
        Serializer qout = new Serializer();
2380
        eval.Run(qout);         
2381
    }
2382

    
2383
}
2384

    
2385
/// <summary>
2386
/// Demonstrate XQuery Update
2387
/// </summary>
2388

    
2389
public class XQueryUpdate : Example
2390
{
2391

    
2392
    public override string testName
2393
    {
2394
        get { return "SA-XQueryUpdate"; }
2395
    }
2396

    
2397
    /// <summary>
2398
    /// Demonstrate XQuery Update
2399
    /// </summary>
2400

    
2401
    public override void run(Uri samplesDir)
2402
    {
2403
        Processor processor = new Processor(true);
2404

    
2405
        DocumentBuilder loader = processor.NewDocumentBuilder();
2406
        loader.BaseUri = new Uri(samplesDir, "data/books.xml");
2407
        loader.TreeModel = TreeModel.LinkedTree;
2408
        XdmNode indoc = loader.Build(new Uri(samplesDir, "data/books.xml"));
2409

    
2410
        Console.Out.WriteLine("=========== BEFORE UPDATE ===========");
2411

    
2412
        Serializer serializer0 = new Serializer();
2413
        serializer0.SetOutputProperty(Serializer.METHOD, "xml");
2414
        serializer0.SetOutputProperty(Serializer.INDENT, "yes");
2415
        serializer0.SetOutputWriter(Console.Out);
2416
        processor.WriteXdmValue(indoc, serializer0);
2417

    
2418
        String query =
2419
            "for $i in //PRICE return \n" +
2420
            "replace value of node $i with $i - 0.05";
2421

    
2422
        XQueryCompiler compiler = processor.NewXQueryCompiler();
2423
        compiler.UpdatingEnabled = true;
2424
        XQueryExecutable exp = compiler.Compile(query);
2425
        XQueryEvaluator eval = exp.Load();
2426
        eval.ContextItem = indoc;
2427
        XdmNode[] updatedNodes = eval.RunUpdate();
2428
        foreach (XdmNode root in updatedNodes)
2429
        {
2430
            Uri documentUri = root.DocumentUri;
2431
            if (documentUri != null && documentUri.Scheme == "file")
2432
            {
2433
                Stream stream = UriConnection.getWritableUriStream(documentUri);
2434
                Serializer serializer = new Serializer();
2435
                serializer.SetOutputProperty(Serializer.METHOD, "xml");
2436
                serializer.SetOutputProperty(Serializer.INDENT, "yes");
2437
                serializer.SetOutputStream(stream);
2438
                processor.WriteXdmValue(root, serializer);
2439
            }
2440
        }
2441

    
2442
        Console.Out.WriteLine("=========== AFTER UPDATE ===========");
2443

    
2444
        processor.WriteXdmValue(indoc, serializer0);
2445
    }
2446
}
2447

    
2448
/// <summary>
2449
/// Show validation of an instance document against a schema
2450
/// </summary>
2451

    
2452
public class Validate : Example
2453
{
2454

    
2455
    public override string testName
2456
    {
2457
        get { return "EE-Validate"; }
2458
    }
2459

    
2460
    /// <summary>
2461
    /// Show validation of an instance document against a schema
2462
    /// </summary>
2463

    
2464
    public override void run(Uri samplesDir)
2465
    {
2466
        // Load a schema
2467

    
2468
        Processor processor;
2469
        try
2470
        {
2471
            processor = new Processor(true);
2472
        }
2473
        catch (Exception err)
2474
        {
2475
            Console.WriteLine(err);
2476
            Console.WriteLine("Failed to load Saxon-EE (use -HE option to run Saxon-HE tests only)");
2477
            return;
2478
        }
2479
        processor.SetProperty("http://saxon.sf.net/feature/timing", "true");
2480
        processor.SetProperty("http://saxon.sf.net/feature/validation-warnings", "true");
2481
        SchemaManager manager = processor.SchemaManager;
2482
        manager.XsdVersion = "1.1";
2483
        manager.ErrorList = new ArrayList();
2484
        Uri schemaUri = new Uri(samplesDir, "data/books.xsd");
2485

    
2486
        try
2487
        {
2488
            manager.Compile(schemaUri);
2489
        }
2490
        catch (Exception e)
2491
        {
2492
            Console.WriteLine(e);
2493
            Console.WriteLine("Schema compilation failed with " + manager.ErrorList.Count + " errors");
2494
            foreach (StaticError error in manager.ErrorList)
2495
            {
2496
                Console.WriteLine("At line " + error.LineNumber + ": " + error.Message);
2497
            }
2498
            return;
2499
        }
2500

    
2501

    
2502
        // Use this to validate an instance document
2503

    
2504
        SchemaValidator validator = manager.NewSchemaValidator();
2505
        //Uri instanceUri = new Uri(samplesDir, "data/books-invalid.xml");
2506
        //validator.SetSource(instanceUri);
2507
        XmlReader xmlReader = XmlReader.Create(samplesDir + "data/books-invalid.xml");
2508
        validator.SetSource(xmlReader);
2509
        validator.ErrorList = new ArrayList();
2510
        XdmDestination psvi = new XdmDestination();
2511
        validator.SetDestination(psvi);
2512

    
2513
        try
2514
        {
2515
            validator.Run();
2516
        }
2517
        catch (Exception e)
2518
        {
2519
            Console.WriteLine(e);
2520
            Console.WriteLine("Instance validation failed with " + validator.ErrorList.Count + " errors");
2521
            foreach (StaticError error in validator.ErrorList)
2522
            {
2523
                Console.WriteLine("At line " + error.LineNumber + ": " + error.Message);
2524
            }
2525
            return;
2526
        }
2527

    
2528
        // Run a query on the result to check that it has type annotations
2529

    
2530
        XQueryCompiler xq = processor.NewXQueryCompiler();
2531
        XQueryEvaluator xv = xq.Compile("data((//PRICE)[1]) instance of xs:decimal").Load();
2532
        xv.ContextItem = psvi.XdmNode;
2533
        Console.WriteLine("Price is decimal? " + xv.EvaluateSingle().ToString());
2534
    }
2535
}
2536

    
2537

    
2538

    
2539
public class UriConnection
2540
{
2541

    
2542
    // Get a stream for reading from a file:// URI
2543

    
2544
    public static Stream getReadableUriStream(Uri uri)
2545
    {
2546
        WebRequest request = (WebRequest)WebRequest.Create(uri);
2547
        return request.GetResponse().GetResponseStream();
2548
    }
2549

    
2550
    // Get a stream for writing to a file:// URI
2551

    
2552
    public static Stream getWritableUriStream(Uri uri)
2553
    {
2554
        FileWebRequest request = (FileWebRequest)WebRequest.CreateDefault(uri);
2555
        request.Method = "POST";
2556
        return request.GetRequestStream();
2557
    }
2558
}
2559

    
2560

    
2561
/// <summary>
2562
/// Place holder for extra test cases you might want to try out
2563
/// </summary>
2564

    
2565
public class ExtraTestCase : Example
2566
{
2567

    
2568
    public override string testName
2569
    {
2570
        get { return "ExtraTestCase"; }
2571
    }
2572

    
2573
    /// <summary>
2574
    /// Place holder for extra test cases you might want to try out
2575
    /// </summary>
2576

    
2577
    public override void run(Uri samplesDir)
2578
    {
2579
        Processor proc = new Processor();
2580
        XsltCompiler compiler = proc.NewXsltCompiler();
2581

    
2582
        XsltTransformer transform = compiler.Compile(new Uri(@"e:\temp\test.xsl")).Load();
2583
        transform.BaseOutputUri = new Uri(@"e:\");
2584
        transform.InitialTemplate = new QName("main");
2585

    
2586
        Serializer serializer = new Serializer();
2587
        serializer.SetOutputWriter(Console.Out);
2588

    
2589
        transform.Run(serializer);
2590

    
2591
    }
2592

    
2593
    
2594

    
2595
}
2596

    
2597

    
2598

    
2599

    
2600

    
2601

    
2602

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

    
2610
public class UserXmlResolver : XmlUrlResolver
2611
{
2612

    
2613
    public String Message = null;
2614

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

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

    
2648
public class UserResultDocumentHandler : IResultDocumentHandler
2649
{
2650

    
2651
    private Hashtable results;
2652

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

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

    
2665
}
2666

    
2667

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

    
2686

    
(3-3/24)