Project

Profile

Help

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

he / tags / 9.6.0.7 / samples / cs / XsltExamples.cs @ c74fd4aa

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

    
7

    
8

    
9
public class XsltExamples {
10

    
11

    
12
    public static void Main(String[] argv) {
13

    
14
        String test = "all";
15

    
16
        if (argv.Length > 0) {
17
            test = argv[0];
18
        }
19

    
20
        String samplesDir;
21

    
22
        if (argv.Length > 1) {
23
            samplesDir = argv[1];
24
        } else {
25
            String home = Environment.GetEnvironmentVariable("SAXON_HOME");
26
            if (home == null) {
27
                Console.WriteLine("No input directory supplied, and SAXON_HOME is not set");
28
                return;
29
            } else {
30
                if (home.EndsWith("/") || home.EndsWith("\\")) {
31
                    samplesDir = home + "samples/";
32
                } else {
33
                    samplesDir = home + "/samples/";
34
                }
35
            }
36
        }
37

    
38
        String dir = samplesDir + "trax/";
39

    
40
        String foo_xml = dir + "xml/foo.xml";
41
        String foo_xsl = dir + "xsl/foo.xsl";
42
        String baz_xml = dir + "xml/baz.xml";
43
        String baz_xsl = dir + "xsl/baz.xsl";
44
        String foo2_xsl = dir + "xsl/foo2.xsl";
45
        String foo3_xsl = dir + "xsl/foo3.xsl";
46
        String text_xsl = dir + "xsl/text.xsl";
47
        String embedded_xml = dir + "xml/embedded.xml";
48
        String multidoc_xsl = dir + "xsl/multidoc.xsl";
49
        String valid_xml = dir + "xml/valid.xml";
50
        String lookup_xsl = dir + "xsl/lookup.xsl";
51

    
52

    
53
        if (test == "all" || test == "ExampleSimple1") {
54
            Console.WriteLine("\n\n==== ExampleSimple1 ====");
55

    
56
            try {
57
                ExampleSimple1(foo_xml, foo_xsl);
58
            } catch (Exception ex) {
59
                handleException(ex);
60
            }
61
        }
62

    
63
        if (test == "all" || test == "ExampleSimple2") {
64
            Console.WriteLine("\n\n==== ExampleSimple2 ====");
65

    
66
            try {
67
                ExampleSimple2(foo_xml, foo_xsl);
68
            } catch (Exception ex) {
69
                handleException(ex);
70
            }
71
        }
72

    
73

    
74
        if (test == "all" || test == "ExampleFromReader") {
75
            Console.WriteLine("\n\n==== ExampleFromReader ====");
76

    
77
            try {
78
                ExampleFromReader(foo_xml, foo_xsl);
79
            } catch (Exception ex) {
80
                handleException(ex);
81
            }
82
        }
83

    
84
        if (test == "all" || test == "ExampleUseTemplatesObj") {
85
            Console.WriteLine("\n\n==== ExampleUseTemplatesObj ====");
86

    
87
            try {
88
                ExampleUseTemplatesObj(foo_xml, baz_xml,
89
                                       foo_xsl);
90
            } catch (Exception ex) {
91
                handleException(ex);
92
            }
93
        }
94

    
95
        if (test == "all" || test == "ExampleSAXResult") {
96
            Console.WriteLine("\n\n==== ExampleSAXResult ====");
97

    
98
            try {
99
                ExampleSAXResult(foo_xml, foo_xsl);
100
            } catch (Exception ex) {
101
                handleException(ex);
102
            }
103
        }
104

    
105
        if (test == "all" || test == "ExampleXMLReader") {
106
            Console.WriteLine("\n\n==== ExampleXMLReader ====");
107

    
108
            try {
109
                ExampleXMLReader(foo_xml, foo_xsl);
110
            } catch (Exception ex) {
111
                handleException(ex);
112
            }
113
        }
114

    
115
        if (test == "all" || test == "ExampleXMLFilter") {
116
            Console.WriteLine("\n\n==== ExampleXMLFilter ====");
117

    
118
            try {
119
                ExampleXMLFilter(foo_xml, foo_xsl);
120
            } catch (Exception ex) {
121
                handleException(ex);
122
            }
123
        }
124

    
125
        if (test == "all" || test == "ExampleXMLFilterChain") {
126
            Console.WriteLine("\n\n==== ExampleXMLFilterChain ====");
127

    
128
            try {
129
                ExampleXMLFilterChain(foo_xml, foo_xsl,
130
                                      foo2_xsl, foo3_xsl);
131
            } catch (Exception ex) {
132
                handleException(ex);
133
            }
134
        }
135

    
136
        if (test == "all" || test == "ExampleSaxonToSaxon") {
137
            Console.WriteLine("\n\n==== ExampleSaxonToSaxon ====");
138

    
139
            try {
140
                ExampleSaxonToSaxon(foo_xml, foo_xsl);
141
            } catch (Exception ex) {
142
                handleException(ex);
143
            }
144
        }
145

    
146
        if (test == "all" || test == "ExampleSaxonToSaxonNonRoot") {
147
            Console.WriteLine("\n\n==== ExampleSaxonToSaxonNonRoot ====");
148

    
149
            try {
150
                ExampleSaxonToSaxonNonRoot(foo_xml, foo_xsl);
151
            } catch (Exception ex) {
152
                handleException(ex);
153
            }
154
        }
155

    
156
        if (test == "all" || test == "ExampleDOMtoDOM") {
157
            Console.WriteLine("\n\n==== ExampleDOMtoDOM (using wrapper) ====");
158

    
159
            try {
160
                ExampleDOMtoDOM(foo_xml, foo_xsl);
161
            } catch (Exception ex) {
162
                handleException(ex);
163
            }
164
        }
165

    
166
        if (test == "all" || test == "ExampleParam") {
167
            Console.WriteLine("\n\n==== ExampleParam ====");
168

    
169
            try {
170
                ExampleParam(foo_xml, foo_xsl);
171
            } catch (Exception ex) {
172
                handleException(ex);
173
            }
174
        }
175

    
176
        if (test == "all" || test == "ExampleTransformerReuse") {
177
            Console.WriteLine("\n\n==== ExampleTransformerReuse ====");
178

    
179
            try {
180
                ExampleTransformerReuse(foo_xml, foo_xsl);
181
            } catch (Exception ex) {
182
                handleException(ex);
183
            }
184
        }
185

    
186
        if (test == "all" || test == "ExampleOutputProperties") {
187
            Console.WriteLine("\n\n==== ExampleOutputProperties ====");
188

    
189
            try {
190
                ExampleOutputProperties(foo_xml, foo_xsl);
191
            } catch (Exception ex) {
192
                handleException(ex);
193
            }
194
        }
195

    
196
        if (test == "all" || test == "ExampleUseAssociated") {
197
            Console.WriteLine("\n\n==== ExampleUseAssociated ====");
198

    
199
            try {
200
                ExampleUseAssociated(foo_xml);
201
            } catch (Exception ex) {
202
                handleException(ex);
203
            }
204
        }
205

    
206
        if (test == "all" || test == "ExampleUseEmbedded") {
207
            Console.WriteLine("\n\n==== ExampleUseEmbedded ====");
208

    
209
            try {
210
                ExampleUseAssociated(embedded_xml);
211
            } catch (Exception ex) {
212
                handleException(ex);
213
            }
214
        }
215

    
216
        if (test == "all" || test == "ExampleDisplayingErrors") {
217
            Console.WriteLine("\n\n==== ExampleDisplayingErrors ====");
218

    
219
            try {
220
                ExampleDisplayingErrors();
221
            } catch (Exception ex) {
222
                handleException(ex);
223
            }
224
        }
225

    
226
        if (test == "all" || test == "ExampleCapturingErrors") {
227
            Console.WriteLine("\n\n==== ExampleCapturingErrors ====");
228

    
229
            try {
230
                ExampleCapturingErrors();
231
            } catch (Exception ex) {
232
                handleException(ex);
233
            }
234
        }
235

    
236

    
237
        if (test == "all" || test == "ExampleUsingURIResolver") {
238
            Console.WriteLine("\n\n==== ExampleUsingURIResolver ====");
239

    
240
            try {
241
                ExampleUsingURIResolver(foo_xml, text_xsl);
242
            } catch (Exception ex) {
243
                handleException(ex);
244
            }
245
        }
246

    
247
        if (test == "all" || test == "ExampleUsingDTD") {
248
            Console.WriteLine("\n\n==== ExampleUsingDTD ====");
249

    
250
            try {
251
                ExampleUsingDTD(valid_xml, lookup_xsl);
252
            } catch (Exception ex) {
253
                handleException(ex);
254
            }
255
        }
256

    
257
        if (test == "all" || test == "ExampleMultipleOutput") {
258
            Console.WriteLine("\n\n==== ExampleMultipleOutput ====");
259

    
260
            try {
261
                ExampleMultipleOutput(foo_xml, multidoc_xsl);
262
            } catch (Exception ex) {
263
                handleException(ex);
264
            }
265
        }
266

    
267
        if (test == "all" || test == "ExampleUsingResultDocumentHandler") {
268
            Console.WriteLine("\n\n==== ExampleUsingResultDocumentHandler ====");
269

    
270
            try {
271
                ExampleUsingResultDocumentHandler(foo_xml, multidoc_xsl);
272
            } catch (Exception ex) {
273
                handleException(ex);
274
            }
275
        }
276

    
277
        if (test == "all" || test == "ExtraTestCase") {
278
            Console.WriteLine("\n\n==== ExtraTestCase ====");
279

    
280
            try {
281
                ExtraTestCase(foo_xml, foo_xsl);
282
            } catch (Exception ex) {
283
                handleException(ex);
284
            }
285
        }
286

    
287
        Console.WriteLine("\n==== done! ====");
288
    }
289

    
290
    /**
291
     * Show the simplest possible transformation from URI of source document
292
     * to output stream.
293
     */
294
    public static void ExampleSimple1(String sourceUri, String xsltUri) {
295

    
296
        // Create a Processor instance.
297
        Processor processor = new Processor();
298

    
299
        // Load the source document
300
        XdmNode input = processor.NewDocumentBuilder().Build(new Uri(sourceUri));
301

    
302
        // Create a transformer for the stylesheet.
303
        XsltTransformer transformer = processor.NewXsltCompiler().Compile(new Uri(xsltUri)).Load();
304

    
305
        // Set the root node of the source document to be the initial context node
306
        transformer.InitialContextNode = input;
307

    
308
        // Create a serializer
309
        Serializer serializer = new Serializer();
310
        serializer.SetOutputWriter(Console.Out);
311

    
312
        // Transform the source XML to System.out.
313
        transformer.Run(serializer);
314
    }
315

    
316

    
317
    /**
318
     * Show the simplest possible transformation from File
319
     * to a File.
320
     */
321
    public static void ExampleSimple2(String sourceUri, String xsltUri) {
322

    
323
        // Create a Processor instance.
324
        Processor processor = new Processor();
325

    
326
        // Load the source document
327
        XdmNode input = processor.NewDocumentBuilder().Build(new Uri(sourceUri));
328

    
329
        // Create a transformer for the stylesheet.
330
        XsltTransformer transformer = processor.NewXsltCompiler().Compile(new Uri(xsltUri)).Load();
331

    
332
        // Set the root node of the source document to be the initial context node
333
        transformer.InitialContextNode = input;
334

    
335
        // Create a serializer
336
        Serializer serializer = new Serializer();
337
        serializer.SetOutputStream(new FileStream("ExampleSimple2.out", FileMode.Create, FileAccess.Write));
338

    
339
        // Transform the source XML to System.out.
340
        transformer.Run(serializer);
341

    
342
        Console.WriteLine("\nOutput written to ExampleSimple2.out\n");
343
    }
344

    
345

    
346
    /**
347
     * Show simple transformation from reader to output stream.  In general
348
     * this use case is discouraged, since the XML encoding can not be
349
     * processed.
350
     */
351
    public static void ExampleFromReader(String sourceUri, String xsltUri) {
352

    
353
        /*        // Create a transform factory instance.
354
                TransformerFactory tfactory = TransformerFactory.newInstance();
355

    
356
                // Note that in this case the XML encoding can not be processed!
357
                Reader       xslReader = new BufferedReader(new FileReader(xsltUri));
358
                StreamSource xslSource = new StreamSource(xslReader);
359

    
360
                // Note that if we don't do this, relative URLs can not be resolved correctly!
361
                xslSource.setSystemId(xsltUri);
362

    
363
                // Create a transformer for the stylesheet.
364
                Transformer transformer = tfactory.newTransformer(xslSource);
365

    
366
                // Note that in this case the XML encoding can not be processed!
367
                Reader       xmlReader = new BufferedReader(new FileReader(sourceUri));
368
                StreamSource xmlSource = new StreamSource(xmlReader);
369

    
370
                // The following line would be needed if the source document contained
371
                // a relative URL
372
                // xmlSource.setSystemId(sourceUri);
373

    
374
                // Transform the source XML to System.out.
375
                transformer.transform(xmlSource, new StreamResult(System.out));*/
376
    }
377

    
378
    /**
379
     * Perform a transformation using a compiled stylesheet (a Templates object)
380
     */
381
    public static void ExampleUseTemplatesObj(
382
            String sourceUri1, String sourceUri2, String xsltUri) {
383

    
384
        // Create a Processor instance.
385
        Processor processor = new Processor();
386

    
387
        // Create a compiled stylesheet
388
        XsltExecutable templates = processor.NewXsltCompiler().Compile(new Uri(xsltUri));
389

    
390
        // Note: we could actually use the same XSltTransformer in this case.
391
        // But in principle, the two transformations could be done in parallel in separate threads.
392

    
393
        // Do the first transformation
394
        Console.WriteLine("\n\n----- transform of " + sourceUri1 + " -----");
395
        XsltTransformer transformer1 = templates.Load();
396
        transformer1.InitialContextNode = processor.NewDocumentBuilder().Build(new Uri(sourceUri1));
397
        transformer1.Run(new Serializer());     // default destination is Console.Out
398

    
399
        // Do the second transformation
400
        Console.WriteLine("\n\n----- transform of " + sourceUri2 + " -----");
401
        XsltTransformer transformer2 = templates.Load();
402
        transformer2.InitialContextNode = processor.NewDocumentBuilder().Build(new Uri(sourceUri2));
403
        transformer2.Run(new Serializer());     // default destination is Console.Out        
404

    
405
    }
406

    
407

    
408
    /**
409
     * Send output to a user-specified ContentHandler.
410
     */
411

    
412
    public static void ExampleSAXResult(
413
            String sourceUri, String xsltUri) {
414

    
415
        /*       TransformerFactory tfactory = TransformerFactory.newInstance();
416

    
417
               // Does this factory support SAX features?
418
               if (tfactory.getFeature(SAXResult.FEATURE)) {
419

    
420
                   // Get a transformer in the normal way:
421
                   Transformer transformer =
422
                       tfactory.newTransformer(new StreamSource(xsltUri));
423

    
424
                   // Get the source as a StreamSource
425
                   Reader       xmlReader = new BufferedReader(new FileReader(sourceUri));
426
                   StreamSource xmlSource = new StreamSource(xmlReader);
427

    
428
                   // Set the result handling to be a serialization to System.out.
429
                   Result result = new SAXResult(new ExampleContentHandler());
430

    
431
                   // Do the transformation
432
                   transformer.transform(xmlSource, result);
433

    
434
               } else {
435
                   Console.WriteLine(
436
                       "Can't do ExampleSAXResult because tfactory is not a SAXTransformerFactory");
437
               }*/
438
    }
439

    
440

    
441
    /**
442
     * Show the Transformer as a SAX2 XMLReader.  An XMLFilter obtained
443
     * from newXMLFilter should act as a transforming XMLReader if setParent is not
444
     * called.  Internally, an XMLReader is created as the parent for the XMLFilter.
445
     */
446
    public static void ExampleXMLReader(String sourceUri, String xsltUri) {
447

    
448
        /*   TransformerFactory tfactory = TransformerFactory.newInstance();
449

    
450
           if (tfactory.getFeature(SAXSource.FEATURE)) {
451
               XMLReader reader =
452
                   ((SAXTransformerFactory) tfactory)
453
                       .newXMLFilter(new StreamSource(new File(xsltUri)));
454

    
455
               reader.setContentHandler(new ExampleContentHandler());
456
               reader.parse(new InputSource(new File(sourceUri).toURL().toString()));
457
           } else {
458
               Console.WriteLine("tfactory does not support SAX features!");
459
           }*/
460
    }
461

    
462
    /**
463
     * Show the Transformer as a simple XMLFilter.  This is pretty similar
464
     * to ExampleXMLReader, except that here the parent XMLReader is created
465
     * by the caller, instead of automatically within the XMLFilter.  This
466
     * gives the caller more direct control over the parent reader.
467
     */
468
    public static void ExampleXMLFilter(String sourceUri, String xsltUri) {
469

    
470
        /*      TransformerFactory tfactory = TransformerFactory.newInstance();
471
              XMLReader reader   = makeXMLReader();
472

    
473

    
474
              // The transformer will use a SAX parser as it's reader.
475

    
476
              try {
477
                  reader.setFeature(
478
                      "http://xml.org/sax/features/namespace-prefixes", true);
479
              } catch (SAXException se) {
480
                  System.err.println("SAX Parser doesn't report namespace prefixes!");
481
                  throw se;
482
              }
483

    
484
              XMLFilter filter =
485
                  ((SAXTransformerFactory) tfactory)
486
                      .newXMLFilter(new StreamSource(new File(xsltUri)));
487

    
488
              filter.setParent(reader);
489
              filter.setContentHandler(new ExampleContentHandler());
490

    
491
              // Now, when you call transformer.parse, it will set itself as
492
              // the content handler for the parser object (it's "parent"), and
493
              // will then call the parse method on the parser.
494
              filter.parse(new InputSource(new File(sourceUri).toURL().toString()));*/
495
    }
496

    
497
    /**
498
     * This Example shows how to chain events from one Transformer
499
     * to another transformer, using the Transformer as a
500
     * SAX2 XMLFilter/XMLReader.
501
     */
502
    public static void ExampleXMLFilterChain(
503
            String sourceUri, String xsltUri_1, String xsltUri_2, String xsltUri_3) {
504

    
505
        // Create a Processor instance.
506
        Processor processor = new Processor();
507

    
508
        // Load the source document
509
        XdmNode input = processor.NewDocumentBuilder().Build(new Uri(sourceUri));
510

    
511
        // Create a compiler
512
        XsltCompiler compiler = processor.NewXsltCompiler();
513

    
514
        // Compile all three stylesheets
515
        XsltTransformer transformer1 = compiler.Compile(new Uri(xsltUri_1)).Load();
516
        XsltTransformer transformer2 = compiler.Compile(new Uri(xsltUri_2)).Load();
517
        XsltTransformer transformer3 = compiler.Compile(new Uri(xsltUri_3)).Load();
518

    
519
        // Now run them in series
520
        transformer1.InitialContextNode = input;
521
        XdmDestination results1 = new XdmDestination();
522
        transformer1.Run(results1);
523
        Console.WriteLine("After phase 1:");
524
        Console.WriteLine(results1.XdmNode.OuterXml);
525

    
526
        transformer2.InitialContextNode = results1.XdmNode;
527
        XdmDestination results2 = new XdmDestination();
528
        transformer2.Run(results2);
529
        Console.WriteLine("After phase 2:");
530
        Console.WriteLine(results2.XdmNode.OuterXml);
531

    
532
        transformer3.InitialContextNode = results2.XdmNode;
533
        //TextWriterDestination results3 = new TextWriterDestination(new XmlTextWriter(Console.Out));
534
        XdmDestination results3 = new XdmDestination();
535
        transformer3.Run(results3);
536
        Console.WriteLine("After phase 3:");
537
        Console.WriteLine(results3.XdmNode.OuterXml);
538

    
539
    }
540

    
541
    /**
542
     * Show how to transform a Saxon tree into another Saxon tree.
543
     */
544
    public static void ExampleSaxonToSaxon(String sourceUri, String xsltUri) {
545

    
546
        // Create a Processor instance.
547
        Processor processor = new Processor();
548

    
549
        // Load the source document
550
        XdmNode input = processor.NewDocumentBuilder().Build(new Uri(sourceUri));
551

    
552
        // Create a compiler
553
        XsltCompiler compiler = processor.NewXsltCompiler();
554

    
555
        // Compile the stylesheet
556
        XsltTransformer transformer = compiler.Compile(new Uri(xsltUri)).Load();
557

    
558
        // Run the transformation
559
        transformer.InitialContextNode = input;
560
        XdmDestination result = new XdmDestination();
561
        transformer.Run(result);
562

    
563
        // Serialize the result so we can see that it worked
564
        StringWriter sw = new StringWriter();
565
        result.XdmNode.WriteTo(new XmlTextWriter(sw));
566
        Console.WriteLine(sw.ToString());
567

    
568
        // Note: we don't do 
569
        //   result.XdmNode.WriteTo(new XmlTextWriter(Console.Out));
570
        // because that results in the Console.out stream being closed, 
571
        // with subsequent attempts to write to it being rejected.
572

    
573
    }
574

    
575
    /**
576
     * Show how to transform a tree starting at a node other than the root.
577
     */
578
    public static void ExampleSaxonToSaxonNonRoot(String sourceUri, String xsltUri) {
579

    
580
        // Create a Processor instance.
581
        Processor processor = new Processor();
582

    
583
        // Load the source document
584
        XdmNode input = processor.NewDocumentBuilder().Build(new Uri(sourceUri));
585

    
586
        // Navigate to the first grandchild
587
        XPathSelector eval = processor.NewXPathCompiler().Compile("/*/*[1]").Load();
588
        eval.ContextItem = input;
589
        input = (XdmNode)eval.EvaluateSingle();
590

    
591
        // Create an XSLT compiler
592
        XsltCompiler compiler = processor.NewXsltCompiler();
593

    
594
        // Compile the stylesheet
595
        XsltTransformer transformer = compiler.Compile(new Uri(xsltUri)).Load();
596

    
597
        // Run the transformation
598
        transformer.InitialContextNode = input;
599
        XdmDestination result = new XdmDestination();
600
        transformer.Run(result);
601

    
602
        // Serialize the result so we can see that it worked
603
        Console.WriteLine(result.XdmNode.OuterXml);
604

    
605
    }
606

    
607

    
608
    /**
609
     * Show how to transform a DOM tree into another DOM tree.
610
     * This uses the System.Xml parser to parse an XML file into a
611
     * DOM, and create an output DOM. In this Example, Saxon uses a
612
     * third-party DOM as both input and output.
613
     */
614
    public static void ExampleDOMtoDOM(String sourceUri, String xsltUri) {
615

    
616
        // Create a Processor instance.
617
        Processor processor = new Processor();
618

    
619
        // Load the source document (in practice, it would already exist as a DOM)
620
        XmlDocument doc = new XmlDocument();
621
        doc.Load(new XmlTextReader(sourceUri));
622
        XdmNode input = processor.NewDocumentBuilder().Wrap(doc);
623

    
624
        // Create a compiler
625
        XsltCompiler compiler = processor.NewXsltCompiler();
626

    
627
        // Compile the stylesheet
628
        XsltTransformer transformer = compiler.Compile(new Uri(xsltUri)).Load();
629

    
630
        // Run the transformation
631
        transformer.InitialContextNode = input;
632
        DomDestination result = new DomDestination();
633
        transformer.Run(result);
634

    
635
        // Serialize the result so we can see that it worked
636
        Console.WriteLine(result.XmlDocument.OuterXml);
637
    }
638

    
639

    
640
    /**
641
     * This shows how to set a parameter for use by the stylesheet. Use
642
     * two transformers to show that different parameters may be set
643
     * on different transformers.
644
     */
645
    public static void ExampleParam(String sourceUri, String xsltUri) {
646

    
647
        // Create a Processor instance.
648
        Processor processor = new Processor();
649

    
650
        // Load the source document
651
        XdmNode input = processor.NewDocumentBuilder().Build(new Uri(sourceUri));
652

    
653
        // Compile the stylesheet
654
        XsltExecutable exec = processor.NewXsltCompiler().Compile(new Uri(xsltUri));
655

    
656
        // Create two transformers with different parameters
657
        XsltTransformer transformer1 = exec.Load();
658
        XsltTransformer transformer2 = exec.Load();
659

    
660
        transformer1.SetParameter(new QName("", "", "a-param"), new XdmAtomicValue("hello to you!"));
661
        transformer2.SetParameter(new QName("", "", "a-param"), new XdmAtomicValue("goodbye to you!"));
662

    
663
        // Now run them both
664
        transformer1.InitialContextNode = input;
665
        XdmDestination results1 = new XdmDestination();
666
        transformer1.Run(results1);
667

    
668
        transformer2.InitialContextNode = input;
669
        XdmDestination results2 = new XdmDestination();
670
        transformer2.Run(results2);
671

    
672
        Console.WriteLine("1: " + results1.XdmNode.StringValue);
673
        Console.WriteLine("2: " + results2.XdmNode.StringValue);
674
    }
675

    
676
    /**
677
     * Show the that a transformer can be reused, and show resetting
678
     * a parameter on the transformer. 
679
     */
680
    public static void ExampleTransformerReuse(String sourceUri, String xsltUri) {
681

    
682
        // Create a Processor instance.
683
        Processor processor = new Processor();
684

    
685
        // Load the source document
686
        XdmNode input = processor.NewDocumentBuilder().Build(new Uri(sourceUri));
687

    
688
        // Compile the stylesheet
689
        XsltExecutable exec = processor.NewXsltCompiler().Compile(new Uri(xsltUri));
690

    
691
        // Create a transformer 
692
        XsltTransformer transformer = exec.Load();
693

    
694
        // Run it once        
695
        transformer.SetParameter(new QName("", "", "a-param"), new XdmAtomicValue("hello to you!"));
696
        transformer.InitialContextNode = input;
697
        XdmDestination results = new XdmDestination();
698
        transformer.Run(results);
699
        Console.WriteLine("1: " + results.XdmNode.StringValue);
700

    
701
        // Run it again        
702
        transformer.SetParameter(new QName("", "", "a-param"), new XdmAtomicValue("hello to me!"));
703
        transformer.InitialContextNode = input;
704
        results.Reset();
705
        transformer.Run(results);
706
        Console.WriteLine("2: " + results.XdmNode.StringValue);
707

    
708
    }
709

    
710
    /**
711
     * Show how to override output properties.
712
     */
713
    public static void ExampleOutputProperties(String sourceUri, String xsltUri) {
714

    
715
        /*      TransformerFactory tfactory  = TransformerFactory.newInstance();
716
              Templates          templates =
717
                  tfactory.newTemplates(new StreamSource(new File(xsltUri)));
718
              Properties         oprops    = templates.getOutputProperties();
719
              oprops.put(OutputKeys.INDENT, "yes");
720

    
721
              Transformer transformer = templates.newTransformer();
722

    
723
              transformer.setOutputProperties(oprops);
724
              transformer.transform(new StreamSource(new File(sourceUri)),
725
                                    new StreamResult(System.out));  */
726
    }
727

    
728
    /**
729
     * Show how to get stylesheets that are associated with a given
730
     * xml document via the xml-stylesheet PI (see http://www.w3.org/TR/xml-stylesheet/).
731
     */
732
    public static void ExampleUseAssociated(String sourceUri) {
733

    
734
        // Create a Processor instance.
735
        Processor processor = new Processor();
736
        XsltExecutable exec;
737

    
738
        // Load the source document
739
        XdmNode input = processor.NewDocumentBuilder().Build(new Uri(sourceUri));
740
        Console.WriteLine("=============== source document ===============");
741
        Console.WriteLine(input.OuterXml);
742
        Console.WriteLine("=========== end of source document ============");
743

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

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

    
750
        XPathSelector eval = processor.NewXPathCompiler().Compile(path).Load();
751
        eval.ContextItem = input;
752
        XdmAtomicValue hrefval = (XdmAtomicValue)eval.EvaluateSingle();
753
        Console.WriteLine("evaluated");
754
        String href = hrefval.ToString();
755

    
756
        if (href == null || href == "") {
757
            Console.WriteLine("No suitable xml-stylesheet processing instruction found");
758
            return;
759

    
760
        } else if (href[0] == '#') {
761

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

    
764
            Console.WriteLine("Locating embedded stylesheet with href = " + href);
765
            String idpath = "id('" + href.Substring(1) + "')";
766
            eval = processor.NewXPathCompiler().Compile(idpath).Load();
767
            eval.ContextItem = input;
768
            XdmNode node = (XdmNode)eval.EvaluateSingle();
769
            if (node == null) {
770
                Console.WriteLine("No element found with ID " + href.Substring(1));
771
                return;
772
            }
773
            exec = processor.NewXsltCompiler().Compile(node);
774

    
775
        } else {
776

    
777
            // The stylesheet is in an external document
778

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

    
781
            // Fetch and compile the referenced stylesheet
782
            exec = processor.NewXsltCompiler().Compile(new Uri(input.BaseUri, href.ToString()));
783
        }
784

    
785
        // Create a transformer 
786
        XsltTransformer transformer = exec.Load();
787

    
788
        // Run it       
789
        transformer.SetParameter(new QName("", "", "a-param"), new XdmAtomicValue("hello to you!"));
790
        transformer.InitialContextNode = input;
791
        XdmDestination results = new XdmDestination();
792
        transformer.Run(results);
793
        Console.WriteLine("1: " + results.XdmNode.StringValue);
794

    
795
    }
796

    
797
    /**
798
     * Show a stylesheet compilation in which errors are displayed to the console
799
     */
800

    
801
    public static void ExampleDisplayingErrors() {
802

    
803
        // Create a Processor instance.
804
        Processor processor = new Processor();
805

    
806
        // Create the XSLT Compiler
807
        XsltCompiler compiler = processor.NewXsltCompiler();
808

    
809

    
810
        // Define a stylesheet containing errors
811
        String stylesheet =
812
            "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0'>\n" +
813
            "<xsl:template name='eee:template'>\n" +
814
            "  <xsl:value-of select='32'/>\n" +
815
            "</xsl:template>\n" +
816
            "<xsl:template name='main'>\n" +
817
            "  <xsl:value-of select='$var'/>\n" +
818
            "</xsl:template>\n" +
819
            "</xsl:stylesheet>";
820

    
821

    
822
        // Attempt to compile the stylesheet and display the errors
823
        try {
824
            compiler.BaseUri = new Uri("http://localhost/stylesheet");
825
            compiler.Compile(new XmlTextReader(new StringReader(stylesheet)));
826
            Console.WriteLine("Stylesheet compilation succeeded");
827
        } catch (Exception) {
828
            Console.WriteLine("Stylesheet compilation failed");
829
        }
830

    
831
    }
832

    
833
    /**
834
     * Show a stylesheet compilation in which errors are captured for processing by
835
     * the calling application.
836
     */
837

    
838
    public static void ExampleCapturingErrors() {
839

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

    
843
        // Create the XSLT Compiler
844
        XsltCompiler compiler = processor.NewXsltCompiler();
845

    
846
        // Create a list to hold the error information
847
        compiler.ErrorList = new ArrayList();
848

    
849
        // Define a stylesheet containing errors
850
        String stylesheet =
851
            "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0'>\n" +
852
            "<xsl:template name='fff:template'>\n" +
853
            "  <xsl:value-of select='32'/>\n" +
854
            "</xsl:template>\n" +
855
            "<xsl:template name='main'>\n" +
856
            "  <xsl:value-of select='$var'/>\n" +
857
            "</xsl:template>\n" +
858
            "</xsl:stylesheet>";
859

    
860

    
861
        // Attempt to compile the stylesheet and display the errors
862
        try {
863
            compiler.BaseUri = new Uri("http://localhost/stylesheet");
864
            compiler.Compile(new XmlTextReader(new StringReader(stylesheet)));
865
            Console.WriteLine("Stylesheet compilation succeeded");
866
        } catch (Exception) {
867
            Console.WriteLine("Stylesheet compilation failed with " + compiler.ErrorList.Count + " errors");
868
            foreach (StaticError error in compiler.ErrorList) {
869
                Console.WriteLine("At line " + error.LineNumber + ": " + error.Message);
870
            }
871
        }
872

    
873
    }
874

    
875
    /**
876
     * Show a transformation using a user-written URI Resolver.
877
     */
878

    
879
    public static void ExampleUsingURIResolver(String sourceUri, String xsltUri) {
880

    
881
        // Create a Processor instance.
882
        Processor processor = new Processor();
883

    
884
        // Load the source document
885
        XdmNode input = processor.NewDocumentBuilder().Build(new Uri(sourceUri));
886

    
887
        // Create a transformer for the stylesheet.
888
        XsltTransformer transformer = processor.NewXsltCompiler().Compile(new Uri(xsltUri)).Load();
889

    
890
        // Set the root node of the source document to be the initial context node
891
        transformer.InitialContextNode = input;
892

    
893
        // Set the user-written XmlResolver
894
        transformer.InputXmlResolver = new UserXmlResolver();
895

    
896
        // Create a serializer
897
        Serializer serializer = new Serializer();
898
        serializer.SetOutputWriter(Console.Out);
899

    
900
        // Transform the source XML to System.out.
901
        transformer.Run(serializer);
902

    
903
    }
904

    
905

    
906
    /**
907
    * A sample XmlResolver. This handles a URI ending with ".txt". It loads the
908
    * text file identified by the URI, assuming it is in ISO-8859-1 encoding,
909
    * and wraps it in a containing doc element.
910
    * If the URI doesn't end with ".txt", it delegates processing
911
    * to the standard XmlResolver.
912
    */
913

    
914
    public class UserXmlResolver : XmlUrlResolver {
915

    
916
        public override object GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn) {
917
            Stream input = (Stream)base.GetEntity(absoluteUri, role, ofObjectToReturn);
918
            if (absoluteUri.ToString().EndsWith(".txt")) {
919
                StreamReader reader = new StreamReader(input);
920
                String content = reader.ReadToEnd();
921
                content = content.Replace("&", "&amp;");
922
                content = content.Replace("<", "&lt;");
923
                content = content.Replace(">", "&gt;");
924
                content = "<doc>" + content + "</doc>";
925
                return new StringReader(content);
926
            } else {
927
                return input;
928
            }
929
        }
930
    }
931

    
932
    /**
933
     * Show a transformation using multiple result documents.
934
     */
935

    
936
    public static void ExampleMultipleOutput(String sourceUri, String xsltUri) {
937
        // Create a Processor instance.
938
        Processor processor = new Processor();
939

    
940
        // Load the source document
941
        XdmNode input = processor.NewDocumentBuilder().Build(new Uri(sourceUri));
942

    
943
        // Create a transformer for the stylesheet.
944
        XsltTransformer transformer = processor.NewXsltCompiler().Compile(new Uri(xsltUri)).Load();
945

    
946
        // Set the root node of the source document to be the initial context node
947
        transformer.InitialContextNode = input;
948

    
949
        // Create a serializer
950
        Serializer serializer = new Serializer();
951
        serializer.SetOutputWriter(Console.Out);
952

    
953
        // Transform the source XML to System.out.
954
        transformer.Run(serializer);
955

    
956

    
957
    }
958

    
959
    /**
960
     * Show a transformation using a DTD-based validation and the id() function.
961
     */
962

    
963
    public static void ExampleUsingDTD(String sourceUri, String xsltUri) {
964

    
965
        // Create a Processor instance
966
        Processor processor = new Processor();
967

    
968
        // Load the source document
969
        DocumentBuilder db = processor.NewDocumentBuilder();
970
        db.DtdValidation = true;
971
        XdmNode input = db.Build(new Uri(sourceUri));
972

    
973
        //Create a transformer for the stylesheet
974
        XsltTransformer transformer =
975
            processor.NewXsltCompiler().Compile(new Uri(xsltUri)).Load();
976

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

    
980
        //Set the destination
981
        XdmDestination results = new XdmDestination();
982
        // Create a serializer
983
        //Serializer results = new Serializer();
984
        //results.SetOutputWriter(Console.Out);
985

    
986

    
987
        // Transform the XML
988
        transformer.Run(results);
989

    
990
        Console.WriteLine(results.XdmNode.ToString());
991

    
992
    }
993

    
994

    
995
    /**
996
     * Show a transformation using a user-written result document handler. This example
997
     * captures each of the result documents in a DOM, and creates a Hashtable that indexes
998
     * the DOM trees according to their absolute URI. On completion, it writes all the DOMs
999
     * to the standard output.
1000
     */
1001

    
1002
    public static void ExampleUsingResultDocumentHandler(String sourceUri, String xsltUri) {
1003
        // Create a Processor instance.
1004
        Processor processor = new Processor();
1005

    
1006
        // Load the source document
1007
        XdmNode input = processor.NewDocumentBuilder().Build(new Uri(sourceUri));
1008

    
1009
        // Create a transformer for the stylesheet.
1010
        XsltTransformer transformer = processor.NewXsltCompiler().Compile(new Uri(xsltUri)).Load();
1011

    
1012
        // Set the root node of the source document to be the initial context node
1013
        transformer.InitialContextNode = input;
1014

    
1015
        // Create a serializer
1016
        Serializer serializer = new Serializer();
1017
        serializer.SetOutputWriter(Console.Out);
1018

    
1019
        // Establish the result document handler
1020
        Hashtable results = new Hashtable();
1021
        transformer.ResultDocumentHandler = new ExampleResultDocumentHandler(results);
1022

    
1023
        // Transform the source XML to System.out.
1024
        transformer.Run(serializer);
1025

    
1026
        // Process the captured DOM results
1027
        foreach (DictionaryEntry entry in results) {
1028
            string uri = (string)entry.Key;
1029
            Console.WriteLine("\nResult File " + uri);
1030
            DomDestination dom = (DomDestination)results[uri];
1031
            Console.Write(dom.XmlDocument.OuterXml);
1032
        }
1033
    }
1034

    
1035
    public class ExampleResultDocumentHandler : IResultDocumentHandler {
1036

    
1037
        private Hashtable results;
1038
        
1039
        public ExampleResultDocumentHandler(Hashtable table) {
1040
            this.results = table;
1041
        }
1042

    
1043
        public XmlDestination HandleResultDocument(string href, Uri baseUri) {
1044
            DomDestination destination = new DomDestination();
1045
            results[href] = destination;
1046
            return destination;
1047
        }
1048

    
1049
    }
1050

    
1051
    /**
1052
     * Add your own test case here
1053
     */
1054

    
1055
    public static void ExtraTestCase(String sourceURI, String xsltUri) {
1056
        //
1057
    }
1058

    
1059

    
1060

    
1061
    private static void handleException(Exception ex) {
1062

    
1063
        Console.WriteLine("EXCEPTION: " + ex);
1064
        Console.WriteLine(ex.StackTrace);
1065

    
1066

    
1067
    }
1068

    
1069

    
1070
}
(5-5/5)