File: TraxExamples.java

package info (click to toggle)
libsaxon-java 1%3A6.5.5-13
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 16,556 kB
  • sloc: java: 36,724; xml: 7,470; makefile: 22; sh: 1
file content (1420 lines) | stat: -rw-r--r-- 57,795 bytes parent folder | download | duplicates (8)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
import javax.xml.transform.*;
import javax.xml.transform.sax.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import javax.xml.parsers.*;

// Needed java classes
import java.io.InputStream;
import java.io.Reader;
import java.io.IOException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileNotFoundException;

import java.util.Properties;

// Needed SAX classes
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.Parser;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.ParserAdapter;
import org.xml.sax.helpers.XMLReaderFactory;
import org.xml.sax.helpers.XMLFilterImpl;
import org.xml.sax.XMLReader;
import org.xml.sax.XMLFilter;
import org.xml.sax.ContentHandler;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.ext.DeclHandler;

// Needed DOM classes
import org.w3c.dom.Node;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

// Needed JAXP classes
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import java.io.BufferedInputStream;    // dml

import java.net.URL;
import java.net.MalformedURLException;


/**
 * Some examples to show how the Simple API for Transformations
 * could be used.
 *
 * @author <a href="mailto:scott_boag@lotus.com">Scott Boag</a>
 */
public class TraxExamples {

    /**
     * Method main
     */
    public static void main(String argv[])
            throws TransformerException, TransformerConfigurationException,
                   IOException, SAXException, ParserConfigurationException,
                   FileNotFoundException {
              
        // MHK note. The SAX interface says that SystemIds must be absolute
        // URLs. This example assumes that relative URLs are OK, and that
        // they are interpreted relative to the current directory. I have
        // modified the Aelfred SAXDriver to make this work, as a number of
        // users had complained that Xalan allowed this and Saxon didn't.

        String test = "all";
        if (argv.length > 0) {
            test = argv[0];
        }

        String foo_xml = "xml/foo.xml";
        String foo_xsl = "xsl/foo.xsl";
        String baz_xml = "xml/baz.xml";
        String baz_xsl = "xsl/baz.xsl";
        String foo2_xsl = "xsl/foo2.xsl";
        String foo3_xsl = "xsl/foo3.xsl";
        String text_xsl = "xsl/text.xsl";
        String embedded_xml = "xml/embedded.xml";              

        if (test.equals("all") || test.equals("exampleParseOnly")) {
            System.out.println("\n\n==== exampleParseOnly ====");
    
            try {
                exampleParseOnly(foo_xml);
            } catch (Exception ex) {
                handleException(ex);
            }
        }
        
        

        if (test.equals("all") || test.equals("exampleSimple1")) {
            System.out.println("\n\n==== exampleSimple1 ====");
    
            try {
                exampleSimple1(foo_xml, foo_xsl);
            } catch (Exception ex) {
                handleException(ex);
            }
        }

        if (test.equals("all") || test.equals("exampleSimple2")) {
            System.out.println("\n\n==== exampleSimple2 ====");
    
            try {
                exampleSimple2(foo_xml, foo_xsl);
            } catch (Exception ex) {
                handleException(ex);
            }
        }

        if (test.equals("all") || test.equals("exampleFromStream")) {
            System.out.println("\n\n==== exampleFromStream ====");
    
            try {
                exampleFromStream(foo_xml, baz_xsl);
            } catch (Exception ex) {
                handleException(ex);
            }
        }

        if (test.equals("all") || test.equals("exampleFromReader")) {
            System.out.println("\n\n==== exampleFromReader ====");
    
            try {
                exampleFromReader(foo_xml, foo_xsl);
            } catch (Exception ex) {
                handleException(ex);
            }
        }

        if (test.equals("all") || test.equals("exampleUseTemplatesObj")) {
            System.out.println("\n\n==== exampleUseTemplatesObj ====");
    
            try {
                exampleUseTemplatesObj(foo_xml, baz_xml,
                                       foo_xsl);
            } catch (Exception ex) {
                handleException(ex);
            }
        }

        if (test.equals("all") || test.equals("exampleUseTemplatesHandler")) {
            System.out.println("\n\n==== exampleUseTemplatesHandler ====");
    
            try {
                (new TraxExamples()).exampleUseTemplatesHandler(foo_xml, foo_xsl);
            } catch (Exception ex) {
                handleException(ex);
            }
        }

        if (test.equals("all") || test.equals("exampleContentHandlerToContentHandler")) {
            System.out
            .println("\n\n==== exampleContentHandlerToContentHandler ====");

            try {
                exampleContentHandlerToContentHandler(foo_xml,
                                                      foo_xsl);
            } catch (Exception ex) {
                handleException(ex);
            }
        }

        if (test.equals("all") || test.equals("exampleXMLReader")) {
            System.out.println("\n\n==== exampleXMLReader ====");
    
            try {
                exampleXMLReader(foo_xml, foo_xsl);
            } catch (Exception ex) {
                handleException(ex);
            }
        }

        if (test.equals("all") || test.equals("exampleXMLFilter")) {
            System.out.println("\n\n==== exampleXMLFilter ====");
    
            try {
                exampleXMLFilter(foo_xml, foo_xsl);
            } catch (Exception ex) {
                handleException(ex);
            }
        }

        if (test.equals("all") || test.equals("exampleXMLFilterChain")) {
            System.out.println("\n\n==== exampleXMLFilterChain ====");
    
            try {
                exampleXMLFilterChain(foo_xml, foo_xsl,
                                      foo2_xsl, foo3_xsl);
            } catch (Exception ex) {
                handleException(ex);
            }
        }

        if (test.equals("all") || test.equals("exampleDOMtoDOM")) {
            System.out.println("\n\n==== exampleDOMtoDOM ====");
    
            try {
                exampleDOMtoDOM(foo_xml, foo_xsl);
            } catch (Exception ex) {
                handleException(ex);
            }
        }

        if (test.equals("all") || test.equals("exampleDOMtoDOMNew")) {
            System.out.println("\n\n==== exampleDOMtoDOMNew ====");
    
            try {
                exampleDOMtoDOMNew(foo_xml, foo_xsl);
            } catch (Exception ex) {
                handleException(ex);
            }
        }

        if (test.equals("all") || test.equals("exampleDOMtoDOMNonRoot")) {
            System.out.println("\n\n==== exampleDOMtoDOMNonRoot ====");
    
            try {
                exampleDOMtoDOMNonRoot(foo_xml, foo_xsl);
            } catch (Exception ex) {
                handleException(ex);
            }
        }

        if (test.equals("all") || test.equals("exampleDOMtoDOMAlien")) {
            System.out.println("\n\n==== exampleDOMtoDOMAlien ====");
    
            try {
                exampleDOMtoDOMAlien(foo_xml, foo_xsl);
            } catch (Exception ex) {
                handleException(ex);
            }
        }
        
        if (test.equals("all") || test.equals("exampleNodeInfo")) {
            System.out.println("\n\n==== exampleNodeInfo ====");
    
            try {
                exampleNodeInfo(foo_xml, foo_xsl);
            } catch (Exception ex) {
                handleException(ex);
            }
        }

        if (test.equals("all") || test.equals("exampleSAXtoDOMNewIdentity")) {
            System.out.println("\n\n==== exampleSAXtoDOMNewIdentity ====");
    
            try {
                exampleSAXtoDOMNewIdentity(foo_xml, foo_xsl);
            } catch (Exception ex) {
                handleException(ex);
            }
        }

        if (test.equals("all") || test.equals("exampleParam")) {
            System.out.println("\n\n==== exampleParam ====");
    
            try {
                exampleParam(foo_xml, foo_xsl);
            } catch (Exception ex) {
                handleException(ex);
            }
        }

        if (test.equals("all") || test.equals("exampleTransformerReuse")) {
            System.out.println("\n\n==== exampleTransformerReuse ====");
    
            try {
                exampleTransformerReuse(foo_xml, foo_xsl);
            } catch (Exception ex) {
                handleException(ex);
            }
        }

        if (test.equals("all") || test.equals("exampleOutputProperties")) {
            System.out.println("\n\n==== exampleOutputProperties ====");
    
            try {
                exampleOutputProperties(foo_xml, foo_xsl);
            } catch (Exception ex) {
                handleException(ex);
            }
        }

        if (test.equals("all") || test.equals("exampleUseAssociated")) {
            System.out.println("\n\n==== exampleUseAssociated ====");
    
            try {
                exampleUseAssociated(foo_xml);
            } catch (Exception ex) {
                handleException(ex);
            }
        }

        if (test.equals("all") || test.equals("exampleUseEmbedded")) {
            System.out.println("\n\n==== exampleUseEmbedded ====");
    
            try {
                exampleUseAssociated(embedded_xml);
            } catch (Exception ex) {
                handleException(ex);
            }
        }

        if (test.equals("all") || test.equals("exampleContentHandlertoDOM")) {
            System.out.println("\n\n==== exampleContentHandlertoDOM ====");
    
            try {
                exampleContentHandlertoDOM(foo_xml, foo_xsl);
            } catch (Exception ex) {
                handleException(ex);
            }
        }

        if (test.equals("all") || test.equals("exampleAsSerializer")) {
            System.out.println("\n\n==== exampleAsSerializer ====");
    
            try {
                exampleAsSerializer(foo_xml, foo_xsl);
            } catch (Exception ex) {
                handleException(ex);
            }
        }

        if (test.equals("all") || test.equals("exampleUsingURIResolver")) {
            System.out.println("\n\n==== exampleUsingURIResolver ====");
    
            try {
                exampleUsingURIResolver(foo_xml, text_xsl);
            } catch (Exception ex) {
                handleException(ex);
            }
        }

        System.out.println("\n==== done! ====");
    }

    /**
     * Show the simplest possible transformation from system id
     * to output stream.
     */
    public static void exampleSimple1(String sourceID, String xslID)
            throws TransformerException, TransformerConfigurationException {

        // Create a transform factory instance.
        TransformerFactory tfactory = TransformerFactory.newInstance();

        // Create a transformer for the stylesheet.
        Transformer transformer =
            tfactory.newTransformer(new StreamSource(xslID));

        // Transform the source XML to System.out.
        transformer.transform(new StreamSource(sourceID),
                              new StreamResult(System.out));
    }

    /**
     * Example that shows XML parsing only (no transformation)
     */
     
    public static void exampleParseOnly(String sourceID) throws Exception {
        System.setProperty("javax.xml.parsers.SAXParserFactory",
                "com.icl.saxon.aelfred.SAXParserFactoryImpl");
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();
        parser.parse(sourceID, new org.xml.sax.helpers.DefaultHandler());
        System.out.println("\nParsing complete\n");
    } 

    /**
     * Show the simplest possible transformation from File
     * to a File.
     */
    public static void exampleSimple2(String sourceID, String xslID)
            throws TransformerException, TransformerConfigurationException {

        // Create a transform factory instance.
        TransformerFactory tfactory = TransformerFactory.newInstance();

        // Create a transformer for the stylesheet.
        Transformer transformer =
            tfactory.newTransformer(new StreamSource(xslID));

        // Transform the source XML to System.out.
        transformer.transform(new StreamSource(sourceID),
                              new StreamResult(new File("exampleSimple2.out")));
                              
        System.out.println("\nOutput written to exampleSimple2.out\n");
    }

    /**
     * Show simple transformation from input stream to output stream.
     */
    public static void exampleFromStream(String sourceID, String xslID)
            throws TransformerException, TransformerConfigurationException,
                   FileNotFoundException, MalformedURLException {

        // Create a transform factory instance.
        TransformerFactory tfactory  = TransformerFactory.newInstance();
        InputStream        xslIS     =
            new BufferedInputStream(new FileInputStream(xslID));
        StreamSource       xslSource = new StreamSource(xslIS);

        // The following line would be necessary if the stylesheet contained
        // an xsl:include or xsl:import with a relative URL
        // xslSource.setSystemId(xslID);

        // Create a transformer for the stylesheet.
        Transformer  transformer = tfactory.newTransformer(xslSource);
        InputStream  xmlIS       =
            new BufferedInputStream(new FileInputStream(sourceID));
        StreamSource xmlSource   = new StreamSource(xmlIS);

        // The following line would be necessary if the source document contained
        // a call on the document() function using a relative URL
        // xmlSource.setSystemId(sourceID);

        // Transform the source XML to System.out.
        transformer.transform(xmlSource, new StreamResult(System.out));
    }

    /**
     * Show simple transformation from reader to output stream.  In general
     * this use case is discouraged, since the XML encoding can not be
     * processed.
     */
    public static void exampleFromReader(String sourceID, String xslID)
            throws TransformerException, TransformerConfigurationException,
                   FileNotFoundException, MalformedURLException {

        // Create a transform factory instance.
        TransformerFactory tfactory = TransformerFactory.newInstance();

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

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

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

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

        // The following line would be needed if the source document contained
        // a relative URL
        // xmlSource.setSystemId(sourceID);

        // Transform the source XML to System.out.
        transformer.transform(xmlSource, new StreamResult(System.out));
    }

    /**
     * Perform a transformation using a compiled stylesheet (a Templates object)
     */
    public static void exampleUseTemplatesObj(
            String sourceID1, String sourceID2, String xslID)
                throws TransformerException,
                       TransformerConfigurationException {

        TransformerFactory tfactory = TransformerFactory.newInstance();

        // Create a templates object, which is the processed, 
        // thread-safe representation of the stylesheet.
        Templates templates = tfactory.newTemplates(new StreamSource(xslID));

        // Illustrate the fact that you can make multiple transformers 
        // from the same template.
        Transformer transformer1 = templates.newTransformer();
        Transformer transformer2 = templates.newTransformer();

        System.out.println("\n\n----- transform of " + sourceID1 + " -----");
        transformer1.transform(new StreamSource(sourceID1),
                               new StreamResult(System.out));
        System.out.println("\n\n----- transform of " + sourceID2 + " -----");
        transformer2.transform(new StreamSource(sourceID2),
                               new StreamResult(System.out));
    }

    /**
     * Perform a transformation using a compiled stylesheet (a Templates object)
     */
    public void exampleUseTemplatesHandler(
            String sourceID, String xslID)
                throws Exception {

        TransformerFactory tfactory = TransformerFactory.newInstance();

        // Does this factory support SAX features?
        if (tfactory.getFeature(SAXSource.FEATURE)) {

            // If so, we can safely cast.
            SAXTransformerFactory stfactory =
                ((SAXTransformerFactory) tfactory);

            // Create a Templates ContentHandler to handle parsing of the
            // stylesheet.
            javax.xml.transform.sax.TemplatesHandler templatesHandler =
                               stfactory.newTemplatesHandler();

            // Create an XMLReader and set its features.
            XMLReader reader = makeXMLReader();
        	reader.setFeature("http://xml.org/sax/features/namespaces", true);
        	reader.setFeature("http://xml.org/sax/features/namespace-prefixes", false);

            // Create a XMLFilter that modifies the stylesheet
            XMLFilter filter = new ModifyStylesheetFilter();
            filter.setParent(reader);

            filter.setContentHandler(templatesHandler);

            // Parse the stylesheet.
            filter.parse(new InputSource(xslID));

            // Get the Templates object (generated during the parsing of the stylesheet)
            // from the TemplatesHandler.
            Templates templates = templatesHandler.getTemplates();
            
            // do the transformation
            templates.newTransformer().transform(
                    new StreamSource(sourceID), new StreamResult(System.out));
                    
        } else {
            System.out.println("Factory doesn't implement SAXTransformerFactory");
        }

    }
    
    private class ModifyStylesheetFilter extends XMLFilterImpl {
        public void startDocument () throws SAXException {
            System.err.println("ModifyStylesheetFilter#startDocument");
            super.startDocument();
        }
        public void startElement (String namespaceURI, String localName,
                          String qName, Attributes atts) throws SAXException {
            String lname = (qName.startsWith("xsl:") ? localName : ("XX" + localName));
            super.startElement(namespaceURI, lname, qName, atts);
        }
        public void endElement (String namespaceURI, String localName,
                          String qName) throws SAXException {
            String lname = (qName.startsWith("xsl:") ? localName : ("XX" + localName));
            super.endElement(namespaceURI, lname, qName);
        }
    }

    /**
     * Show the Transformer using SAX events in and SAX events out.
     */
    public static void exampleContentHandlerToContentHandler(
            String sourceID, String xslID)
                throws TransformerException,
                       TransformerConfigurationException, SAXException,
                       IOException, MalformedURLException {

        TransformerFactory tfactory = TransformerFactory.newInstance();

        // Does this factory support SAX features?
        if (tfactory.getFeature(SAXSource.FEATURE)) {

            // If so, we can safely cast.
            SAXTransformerFactory stfactory =
                ((SAXTransformerFactory) tfactory);

            // A TransformerHandler is a ContentHandler that will listen for 
            // SAX events, and transform them to the result.
            TransformerHandler handler =
                stfactory.newTransformerHandler(new StreamSource(xslID));

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

            handler.setResult(result);

            // Create a reader, and set it's content handler to be the TransformerHandler.
            XMLReader reader = makeXMLReader();

            reader.setContentHandler(handler);

            // It's a good idea for the parser to send lexical events.
            // The TransformerHandler is also a LexicalHandler.
            reader.setProperty(
                "http://xml.org/sax/properties/lexical-handler", handler);

            // Parse the source XML, and send the parse events to the TransformerHandler.
            reader.parse(sourceID);
        } else {
            System.out.println(
                "Can't do exampleContentHandlerToContentHandler because tfactory is not a SAXTransformerFactory");
        }
    }

    /**
     * Show the Transformer as a SAX2 XMLReader.  An XMLFilter obtained
     * from newXMLFilter should act as a transforming XMLReader if setParent is not
     * called.  Internally, an XMLReader is created as the parent for the XMLFilter.
     */
    public static void exampleXMLReader(String sourceID, String xslID)
            throws TransformerException, TransformerConfigurationException,
                   SAXException, IOException, MalformedURLException
                       // , ParserConfigurationException
    {

        TransformerFactory tfactory = TransformerFactory.newInstance();

        if (tfactory.getFeature(SAXSource.FEATURE)) {
            XMLReader reader =
                ((SAXTransformerFactory) tfactory)
                    .newXMLFilter(new StreamSource(new File(xslID)));

            reader.setContentHandler(new ExampleContentHandler());
            reader.parse(new InputSource(new File(sourceID).toURL().toString()));
        } else {
            System.out.println("tfactory does not support SAX features!");
        }
    }

    /**
     * Show the Transformer as a simple XMLFilter.  This is pretty similar
     * to exampleXMLReader, except that here the parent XMLReader is created
     * by the caller, instead of automatically within the XMLFilter.  This
     * gives the caller more direct control over the parent reader.
     */
    public static void exampleXMLFilter(String sourceID, String xslID)
            throws TransformerException, TransformerConfigurationException,
                   SAXException, IOException, MalformedURLException
                       // , ParserConfigurationException
    {

        TransformerFactory tfactory = TransformerFactory.newInstance();
        XMLReader reader   = makeXMLReader();


        // The transformer will use a SAX parser as it's reader.
        // LOOKS WRONG: should be set on filter, see below!    
        // reader.setContentHandler(new ExampleContentHandler());

        try {
            reader.setFeature(
                "http://xml.org/sax/features/namespace-prefixes", true);
            reader.setFeature(
                "http://apache.org/xml/features/validation/dynamic", true);
        } catch (SAXException se) {

            // What can we do?
            // TODO: User diagnostics.
        }

        XMLFilter filter =
            ((SAXTransformerFactory) tfactory)
                .newXMLFilter(new StreamSource(new File(xslID)));

        filter.setParent(reader);
        filter.setContentHandler(new ExampleContentHandler());

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

    /**
     * This example shows how to chain events from one Transformer
     * to another transformer, using the Transformer as a
     * SAX2 XMLFilter/XMLReader.
     */
    public static void exampleXMLFilterChain(
            String sourceID, String xslID_1, String xslID_2, String xslID_3)
                throws TransformerException,
                       TransformerConfigurationException, SAXException,
                       IOException, MalformedURLException {

        TransformerFactory tfactory     = TransformerFactory.newInstance();
        Templates          stylesheet1  =
            tfactory.newTemplates(new StreamSource(new File(xslID_1)));
        Transformer        transformer1 = stylesheet1.newTransformer();

        // If one success, assume all will succeed.
        if (tfactory.getFeature(SAXSource.FEATURE)) {
            SAXTransformerFactory stf    = (SAXTransformerFactory) tfactory;
            XMLReader reader   = makeXMLReader();

            XMLFilter filter1 = stf.newXMLFilter(new StreamSource(new File(xslID_1)));
            XMLFilter filter2 = stf.newXMLFilter(new StreamSource(new File(xslID_2)));
            XMLFilter filter3 = stf.newXMLFilter(new StreamSource(new File(xslID_3)));

            if (null != filter1)    // If one success, assume all were success.
            {

                // transformer1 will use a SAX parser as it's reader.    
                filter1.setParent(reader);

                // transformer2 will use transformer1 as it's reader.
                filter2.setParent(filter1);

                // transformer3 will use transformer2 as it's reader.
                filter3.setParent(filter2);
                filter3.setContentHandler(new ExampleContentHandler());

                // filter3.setContentHandler(new org.xml.sax.helpers.DefaultHandler());
                // Now, when you call transformer3 to parse, it will set  
                // itself as the ContentHandler for transform2, and 
                // call transform2.parse, which will set itself as the 
                // content handler for transform1, and call transform1.parse, 
                // which will set itself as the content listener for the 
                // SAX parser, and call parser.parse(new InputSource(foo_xml)).
                filter3.parse(new InputSource(new File(sourceID).toURL().toString()));
            } else {
                System.out
                    .println("Can't do exampleXMLFilter because "
                             + "tfactory doesn't support newXMLFilter()");
            }
        } else {
            System.out.println("Can't do exampleXMLFilter because "
                               + "tfactory is not a SAXTransformerFactory");
        }
    }

    /**
     * Show how to transform a DOM tree into another DOM tree.
     * This uses the javax.xml.parsers to parse an XML file into a
     * DOM, and create an output DOM.
     */
    public static Node exampleDOMtoDOM(String sourceID, String xslID)
            throws TransformerException, TransformerConfigurationException,
                   SAXException, IOException, ParserConfigurationException,
                   MalformedURLException {

        TransformerFactory tfactory = TransformerFactory.newInstance();

        if (tfactory.getFeature(DOMSource.FEATURE)) {
            Templates templates;

            {
                System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
                     "com.icl.saxon.om.DocumentBuilderFactoryImpl");
                DocumentBuilderFactory dfactory =
                    DocumentBuilderFactory.newInstance();
                    System.err.println("Using DocumentBuilderFactory " + dfactory.getClass());

                dfactory.setNamespaceAware(true);

                DocumentBuilder docBuilder =
                    dfactory.newDocumentBuilder();
                    System.err.println("Using DocumentBuilder " + docBuilder.getClass());
                org.w3c.dom.Document outNode    = docBuilder.newDocument();
                
                Node doc =
                    docBuilder.parse(new InputSource(new File(xslID).toURL().toString()));
                System.err.println("Stylesheet document built OK");
                DOMSource dsource = new DOMSource(doc);

                // If we don't do this, the transformer won't know how to 
                // resolve relative URLs in the stylesheet.
                dsource.setSystemId(new File(xslID).toURL().toString());

                templates = tfactory.newTemplates(dsource);
            }

            Transformer transformer = templates.newTransformer();
            DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = dfactory.newDocumentBuilder();
            org.w3c.dom.Document outNode = docBuilder.newDocument();
            Node doc = docBuilder.parse(
                          new InputSource(new File(sourceID).toURL().toString()));

            System.err.println("Source document built OK");
            
            // added by MHK
            DOMSource ds = new DOMSource(doc);
            ds.setSystemId(new File(sourceID).toURL().toString());
            // end of addition
            transformer.transform(ds, new DOMResult(outNode));
            System.err.println("Transformation done OK");
            
            // Serialize the output so we can see the transformation actually worked
            Transformer serializer = tfactory.newTransformer();

            serializer.transform(new DOMSource(outNode),
                                 new StreamResult(System.out));

            return outNode;
        } else {
            throw new org.xml.sax.SAXNotSupportedException(
                "DOM node processing not supported!");
        }
    }

    /**
     * Show how to transform a DOM tree into another DOM tree.
     * This uses the javax.xml.parsers to parse an XML file into the source
     * DOM; it leaves the XSLT processor to create the result DOM.
     */
    public static void exampleDOMtoDOMNew(String sourceID, String xslID)
            throws TransformerException, TransformerConfigurationException,
                   SAXException, IOException, ParserConfigurationException,
                   MalformedURLException {

        TransformerFactory tfactory = TransformerFactory.newInstance();

        if (tfactory.getFeature(DOMSource.FEATURE)) {
            Templates templates;

            {
                System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
                     "com.icl.saxon.om.DocumentBuilderFactoryImpl");
                DocumentBuilderFactory dfactory =
                    DocumentBuilderFactory.newInstance();
                    System.err.println("Using DocumentBuilderFactory " + dfactory.getClass());

                dfactory.setNamespaceAware(true);

                DocumentBuilder docBuilder =
                    dfactory.newDocumentBuilder();
                    System.err.println("Using DocumentBuilder " + docBuilder.getClass());
                org.w3c.dom.Document outNode    = docBuilder.newDocument();
                
                Node doc =
                    docBuilder.parse(new InputSource(new File(xslID).toURL().toString()));
                System.err.println("Stylesheet document built OK");
                DOMSource dsource = new DOMSource(doc);

                // If we don't do this, the transformer won't know how to 
                // resolve relative URLs in the stylesheet.
                dsource.setSystemId(new File(xslID).toURL().toString());

                templates = tfactory.newTemplates(dsource);
            }

            Transformer transformer = templates.newTransformer();
            DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = dfactory.newDocumentBuilder();
            //org.w3c.dom.Document outNode = docBuilder.newDocument();
            Node doc = docBuilder.parse(
                          new InputSource(new File(sourceID).toURL().toString()));

            System.err.println("Source document built OK");
            
            // added by MHK
            DOMSource ds = new DOMSource(doc);
            //ds.setSystemId(new File(sourceID).toURL().toString());
            // end of addition
            DOMResult result = new DOMResult();
            transformer.transform(ds, result);
            System.err.println("Transformation done OK");
            
            // Serialize the output so we can see the transformation actually worked
            Transformer serializer = tfactory.newTransformer();

            serializer.transform(new DOMSource(result.getNode()),
                                 new StreamResult(System.out));
                                 
            int k = result.getNode().getChildNodes().getLength();
            System.err.println("Result root has " + k + " children");

        } else {
            throw new org.xml.sax.SAXNotSupportedException(
                "DOM node processing not supported!");
        }
    }

    /**
     * Show how to transform a DOM tree into another DOM tree.
     * This uses the javax.xml.parsers to parse an XML file into a
     * DOM, and create an output DOM. In this example, the start node
     * for the transformation is an element, not the root node.
     */
    public static Node exampleDOMtoDOMNonRoot(String sourceID, String xslID)
            throws TransformerException, TransformerConfigurationException,
                   SAXException, IOException, ParserConfigurationException,
                   MalformedURLException {

        TransformerFactory tfactory = TransformerFactory.newInstance();

        if (tfactory.getFeature(DOMSource.FEATURE)) {
            Templates templates;

            {
                System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
                     "com.icl.saxon.om.DocumentBuilderFactoryImpl");
                     
                DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
                    System.err.println("Using DocumentBuilderFactory " + dfactory.getClass());

                dfactory.setNamespaceAware(true);

                DocumentBuilder docBuilder = dfactory.newDocumentBuilder();
                    System.err.println("Using DocumentBuilder " + docBuilder.getClass());
                org.w3c.dom.Document outNode    = docBuilder.newDocument();
                
                Node doc =
                    docBuilder.parse(new InputSource(new File(xslID).toURL().toString()));
                System.err.println("Stylesheet document built OK");
                DOMSource dsource = new DOMSource(doc);

                // If we don't do this, the transformer won't know how to 
                // resolve relative URLs in the stylesheet.
                dsource.setSystemId(new File(xslID).toURL().toString());

                templates = tfactory.newTemplates(dsource);
            }

            Transformer transformer = templates.newTransformer();
            DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = dfactory.newDocumentBuilder();
            Document outNode = docBuilder.newDocument();
            Document doc = docBuilder.parse(
                          new InputSource(new File(sourceID).toURL().toString()));
            Node bar = doc.getDocumentElement().getFirstChild();
            while (bar.getNodeType() != Node.ELEMENT_NODE) {
                bar = bar.getNextSibling();
            }

            System.err.println("Source document built OK");
            
            // added by MHK
            DOMSource ds = new DOMSource(bar);
            ds.setSystemId(new File(sourceID).toURL().toString());
            // end of addition
            transformer.transform(ds, new DOMResult(outNode));
            System.err.println("Transformation done OK");
            
            // Serialize the output so we can see the transformation actually worked
            Transformer serializer = tfactory.newTransformer();

            serializer.transform(new DOMSource(outNode),
                                 new StreamResult(System.out));

            return outNode;
        } else {
            throw new org.xml.sax.SAXNotSupportedException(
                "DOM node processing not supported!");
        }
    }


    /**
     * Show how to transform a DOM tree into another DOM tree.
     * This uses the javax.xml.parsers to parse an XML file into a
     * DOM, and create an output DOM. In this example, Saxon uses a
     * third-party DOM as both input and output.
     */
    public static void exampleDOMtoDOMAlien(String sourceID, String xslID)
            throws TransformerException, TransformerConfigurationException,
                   SAXException, IOException, ParserConfigurationException,
                   MalformedURLException {

        String factory = null;

        // Try the crimson parser
        try {
            Class.forName("org.apache.crimson.jaxp.DocumentBuilderFactoryImpl");
            factory = "org.apache.crimson.jaxp.DocumentBuilderFactoryImpl";
        }
        catch (Exception e) {
            factory = null;
        }

        // Try the Xerces parser        
        if (factory==null) {
            try {
                Class.forName("org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
                factory = "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl";
            }
            catch (Exception e) {
                factory = null;
            }
        }
        
        if (factory==null) {
            System.err.println("No third-party DOM Builder found");
            return;
        }
        
        System.setProperty("javax.xml.parsers.DocumentBuilderFactory", factory);
        
        TransformerFactory tfactory = TransformerFactory.newInstance();

        if (tfactory.getFeature(DOMSource.FEATURE)) {
            Templates templates;

            {
                DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
                    System.err.println("Using DocumentBuilderFactory " + dfactory.getClass());

                dfactory.setNamespaceAware(true);

                DocumentBuilder docBuilder = dfactory.newDocumentBuilder();
                    System.err.println("Using DocumentBuilder " + docBuilder.getClass());
                org.w3c.dom.Document outNode    = docBuilder.newDocument();
                
                Node doc =
                    docBuilder.parse(new InputSource(new File(xslID).toURL().toString()));
                System.err.println("Stylesheet document built OK");
                DOMSource dsource = new DOMSource(doc);

                // If we don't do this, the transformer won't know how to 
                // resolve relative URLs in the stylesheet.
                dsource.setSystemId(new File(xslID).toURL().toString());

                templates = tfactory.newTemplates(dsource);
            }

            Transformer transformer = templates.newTransformer();
            DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = dfactory.newDocumentBuilder();

            Document doc = docBuilder.parse(
                          new InputSource(new File(sourceID).toURL().toString()));
            Node bar = doc.getDocumentElement().getFirstChild();
            while (bar.getNodeType() != Node.ELEMENT_NODE) {
                bar = bar.getNextSibling();
            }

            System.err.println("Source document built OK");
            
            // added by MHK
            DOMSource ds = new DOMSource(bar);
            ds.setSystemId(new File(sourceID).toURL().toString());
            // end of addition

            // create a skeleton output document, to which
            // the transformation results will be added

            Document out = docBuilder.newDocument();
            Element extra = out.createElement("extra");
            out.appendChild(extra);


            transformer.transform(ds, new DOMResult(extra));
            System.err.println("Transformation done OK");
            
            // Serialize the output so we can see the transformation actually worked
            Transformer serializer = tfactory.newTransformer();

            serializer.transform(new DOMSource(out),
                                 new StreamResult(System.out));

            return;
        } else {
            throw new org.xml.sax.SAXNotSupportedException(
                "DOM node processing not supported!");
        }
    }


    /**
     * Identity transformation from a SAX Source to a new DOM result.
     * This leaves the XSLT processor to create the result DOM.
     */
    public static void exampleSAXtoDOMNewIdentity(String sourceID, String xslID)
            throws TransformerException, TransformerConfigurationException,
                   SAXException, IOException, ParserConfigurationException,
                   MalformedURLException {

        TransformerFactory tfactory = TransformerFactory.newInstance();
        Transformer transformer = tfactory.newTransformer();
        SAXSource source = new SAXSource(new InputSource(sourceID));
        DOMResult result = new DOMResult();
        transformer.transform(source, result);

        System.err.println("Transformation done OK");
        
        // Serialize the output so we can see the transformation actually worked
        Transformer serializer = tfactory.newTransformer();

        serializer.transform(new DOMSource(result.getNode()),
                             new StreamResult(System.out));
                             
        int k = result.getNode().getChildNodes().getLength();
        System.err.println("Result root has " + k + " children");

    }

    /**
     * Show how to transform directly from a Saxon NodeInfo object.
     * This example is peculiar to Saxon: it is not pure JAXP.
     */
    public static void exampleNodeInfo(String sourceID, String xslID)
            throws TransformerException, TransformerConfigurationException,
                   SAXException, IOException, ParserConfigurationException,
                   MalformedURLException {

        TransformerFactory tfactory = TransformerFactory.newInstance();
        Templates templates = tfactory.newTemplates(new StreamSource(xslID));
        Transformer transformer = templates.newTransformer();
        com.icl.saxon.om.Builder builder =
            ((com.icl.saxon.Controller)transformer).makeBuilder();
        com.icl.saxon.om.DocumentInfo doc =
            builder.build(new SAXSource(new InputSource(sourceID)));
        transformer.transform(doc, new StreamResult(System.out));
    }


    /**
     * This shows how to set a parameter for use by the templates. Use
     * two transformers to show that different parameters may be set
     * on different transformers.
     */
    public static void exampleParam(String sourceID, String xslID)
            throws TransformerException, TransformerConfigurationException {

        TransformerFactory tfactory     = TransformerFactory.newInstance();
        Templates          templates    =
            tfactory.newTemplates(new StreamSource(new File(xslID)));
        Transformer        transformer1 = templates.newTransformer();
        Transformer        transformer2 = templates.newTransformer();

        transformer1.setParameter("a-param", "hello to you!");
        transformer1.transform(new StreamSource(new File(sourceID)),
                               new StreamResult(System.out));
        System.out.println("\n========= (and again with a different parameter value) ===");
        transformer1.setParameter("a-param", "goodbye to you!");
        transformer1.transform(new StreamSource(new File(sourceID)),
                               new StreamResult(System.out));
        System.out.println("\n========= (and again with a no parameter value) ===");                       
        transformer2.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer2.transform(new StreamSource(new File(sourceID)),
                               new StreamResult(System.out));
    }

    /**
     * Show the that a transformer can be reused, and show resetting
     * a parameter on the transformer.
     */
    public static void exampleTransformerReuse(String sourceID, String xslID)
            throws TransformerException, TransformerConfigurationException {

        // Create a transform factory instance.
        TransformerFactory tfactory = TransformerFactory.newInstance();

        // Create a transformer for the stylesheet.
        Transformer transformer =
            tfactory.newTransformer(new StreamSource(new File(xslID)));

        transformer.setParameter("a-param", "hello to you!");

        // Transform the source XML to System.out.
        transformer.transform(new StreamSource(new File(sourceID)),
                              new StreamResult(System.out));
        System.out.println("\n=========\n");
        transformer.setParameter("a-param", "hello to me!");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        // Transform the source XML to System.out.
        transformer.transform(new StreamSource(new File(sourceID)),
                              new StreamResult(System.out));
    }

    /**
     * Show how to override output properties.
     */
    public static void exampleOutputProperties(String sourceID, String xslID)
            throws TransformerException, TransformerConfigurationException {

        TransformerFactory tfactory  = TransformerFactory.newInstance();
        Templates          templates =
            tfactory.newTemplates(new StreamSource(new File(xslID)));
        Properties         oprops    = templates.getOutputProperties();

        oprops.put(OutputKeys.INDENT, "yes");

        Transformer transformer = templates.newTransformer();

        transformer.setOutputProperties(oprops);
        transformer.transform(new StreamSource(new File(sourceID)),
                              new StreamResult(System.out));
    }

    /**
     * Show how to get stylesheets that are associated with a given
     * xml document via the xml-stylesheet PI (see http://www.w3.org/TR/xml-stylesheet/).
     */
    public static void exampleUseAssociated(String sourceID)
            throws TransformerException, TransformerConfigurationException {

        TransformerFactory tfactory = TransformerFactory.newInstance();

        // The DOM tfactory will have it's own way, based on DOM2, 
        // of getting associated stylesheets.
        if (tfactory instanceof SAXTransformerFactory) {
            SAXTransformerFactory stf     =
                ((SAXTransformerFactory) tfactory);
            Source                sources =
                stf.getAssociatedStylesheet(new StreamSource(sourceID), null,
                                            null, null);

            if (null != sources) {
                Transformer transformer = tfactory.newTransformer(sources);

                transformer.transform(new StreamSource(sourceID),
                                      new StreamResult(System.out));
            } else {
                System.out.println("Can't find the associated stylesheet!");
            }
        }
    }

    /**
     * Show the Transformer using SAX events in and DOM nodes out.
     */
    public static void exampleContentHandlertoDOM(
            String sourceID, String xslID)
                throws TransformerException,
                       TransformerConfigurationException, SAXException,
                       IOException, ParserConfigurationException {

        TransformerFactory tfactory = TransformerFactory.newInstance();

        // Make sure the transformer factory we obtained supports both
        // DOM and SAX.
        if (tfactory.getFeature(SAXSource.FEATURE)
                && tfactory.getFeature(DOMSource.FEATURE)) {

            // We can now safely cast to a SAXTransformerFactory.
            SAXTransformerFactory sfactory = (SAXTransformerFactory) tfactory;

            // Create an Document node as the root for the output.
            DocumentBuilderFactory dfactory   =
                DocumentBuilderFactory.newInstance();
            DocumentBuilder        docBuilder = dfactory.newDocumentBuilder();
            org.w3c.dom.Document   outNode    = docBuilder.newDocument();

            // Create a ContentHandler that can liston to SAX events 
            // and transform the output to DOM nodes.
            TransformerHandler handler =
                sfactory.newTransformerHandler(new StreamSource(xslID));

            handler.setResult(new DOMResult(outNode));

            // Create a reader and set it's ContentHandler to be the 
            // transformer.
            XMLReader reader   = makeXMLReader();

            reader.setContentHandler(handler);
            reader.setProperty(
                "http://xml.org/sax/properties/lexical-handler", handler);

            // Send the SAX events from the parser to the transformer,
            // and thus to the DOM tree.
            reader.parse(sourceID);

            // Serialize the node for diagnosis.
            exampleSerializeNode(outNode);
        } else {
            System.out.println(
                "Can't do exampleContentHandlerToContentHandler because tfactory is not a SAXTransformerFactory");
        }
    }

    /**
     * Show a transformation using a user-written URI Resolver.
     */
     
    public static void exampleUsingURIResolver(String sourceID, String xslID)
            throws TransformerException, TransformerConfigurationException {

        // Create a transform factory instance.
        TransformerFactory tfactory = TransformerFactory.newInstance();

        // Create a transformer for the stylesheet.
        Transformer transformer =
            tfactory.newTransformer(new StreamSource(xslID));
            
        // Set the URIResolver
        transformer.setURIResolver(new UserURIResolver(transformer));

        // Transform the source XML to System.out.
        transformer.transform(new StreamSource(sourceID),
                              new StreamResult(System.out));
                              
    }

    /**
    * A sample URIResolver. This handles a URI ending with ".txt". It loads the
    * text file identified by the URI, assuming it is in ISO-8859-1 encoding,
    * into a tree containing a single text node. It returns this
    * result tree to the transformer, exploiting the fact that a Saxon NodeInfo
    * can be used as a Source. If the URI doesn't end with ".txt", it hands over
    * to the standard URI resolver by returning null.
    */
    
    public static class UserURIResolver implements URIResolver {

        Transformer transformer;
        public UserURIResolver(Transformer t) {
            transformer = t;
        }
    
        /**
        * Resolve a URI
        * @param baseURI The base URI that should be used. May be null if uri is absolute.
        * @params uri The relative or absolute URI. May be an empty string. May contain
        * a fragment identifier starting with "#", which must be the value of an ID attribute
        * in the referenced XML document.
        * @return a Source object representing an XML document
        */
    
        public Source resolve(String href, String base)
        throws TransformerException {
            if (href.endsWith(".txt")) {
                try {
                    URL url = new URL(new URL(base), href);
                    java.io.InputStream in = url.openConnection().getInputStream();
                    java.io.InputStreamReader reader = 
                        new java.io.InputStreamReader(in, "iso-8859-1");
                    
                    // this could be vastly more efficient, but it doesn't matter here
                    
                    StringBuffer sb = new StringBuffer();
                    while (true) {
                        int c = reader.read();
                        if (c<0) break;
                        sb.append((char)c);
                    }
                    com.icl.saxon.expr.TextFragmentValue tree = 
                        new com.icl.saxon.expr.TextFragmentValue(
                            sb.toString(), url.toString(),
                            (com.icl.saxon.Controller)transformer);
                    return tree.getFirst();
                } catch (Exception err) {
                    throw new TransformerException(err);
                }
            } else {
                return null;
            }
        } 
        
    } // end of inner class UserURIResolver           


    /**
     * Serialize a node to System.out.
     */
    public static void exampleSerializeNode(Node node)
            throws TransformerException, TransformerConfigurationException,
                   SAXException, IOException, ParserConfigurationException {

        TransformerFactory tfactory = TransformerFactory.newInstance();

        // This creates a transformer that does a simple identity transform, 
        // and thus can be used for all intents and purposes as a serializer.
        Transformer serializer = tfactory.newTransformer();

        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        serializer.transform(new DOMSource(node),
                             new StreamResult(System.out));
    }

    /**
     * A fuller example showing how the TrAX interface can be used
     * to serialize a DOM tree.
     */
    public static void exampleAsSerializer(String sourceID, String xslID)
            throws TransformerException, TransformerConfigurationException,
                   SAXException, IOException, ParserConfigurationException {

        DocumentBuilderFactory dfactory   =
            DocumentBuilderFactory.newInstance();
        DocumentBuilder        docBuilder = dfactory.newDocumentBuilder();
        org.w3c.dom.Document   outNode    = docBuilder.newDocument();
        Node                   doc        =
            docBuilder.parse(new InputSource(sourceID));
        TransformerFactory     tfactory   = TransformerFactory.newInstance();

        // This creates a transformer that does a simple identity transform, 
        // and thus can be used for all intents and purposes as a serializer.
        Transformer serializer = tfactory.newTransformer();
        Properties  oprops     = new Properties();

        oprops.put("method", "html");
        oprops.put("{http://icl.com/saxon}indent-spaces", "2");
        serializer.setOutputProperties(oprops);
        serializer.transform(new DOMSource(doc),
                             new StreamResult(System.out));
    }

    private static void handleException(Exception ex) {

        System.out.println("EXCEPTION: " + ex);
        ex.printStackTrace();

        if (ex instanceof TransformerConfigurationException) {
            System.out.println();
            System.out.println("Test failed");

            Throwable ex1 =
                ((TransformerConfigurationException) ex).getException();
                
            if (ex1!=null) {    // added by MHK
                ex1.printStackTrace();
    
                if (ex1 instanceof SAXException) {
                    Exception ex2 = ((SAXException) ex1).getException();
    
                    System.out.println("Internal sub-exception: ");
                    ex2.printStackTrace();
                }
            }
        }
    }
    
    /**
    * Make an XMLReader
    */
    
    private static XMLReader makeXMLReader() {
        return new com.icl.saxon.aelfred.SAXDriver();
    }
}