KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > TraxExamples


1 import javax.xml.transform.*;
2 import javax.xml.transform.sax.*;
3 import javax.xml.transform.dom.*;
4 import javax.xml.transform.stream.*;
5 import javax.xml.parsers.*;
6
7 // Needed java classes
8
import java.io.InputStream JavaDoc;
9 import java.io.Reader JavaDoc;
10 import java.io.IOException JavaDoc;
11 import java.io.File JavaDoc;
12 import java.io.FileInputStream JavaDoc;
13 import java.io.FileReader JavaDoc;
14 import java.io.BufferedInputStream JavaDoc;
15 import java.io.BufferedReader JavaDoc;
16 import java.io.FileNotFoundException JavaDoc;
17
18 import java.util.Properties JavaDoc;
19
20 // Needed SAX classes
21
import org.xml.sax.InputSource JavaDoc;
22 import org.xml.sax.SAXException JavaDoc;
23 import org.xml.sax.Parser JavaDoc;
24 import org.xml.sax.Attributes JavaDoc;
25 import org.xml.sax.helpers.ParserAdapter JavaDoc;
26 import org.xml.sax.helpers.XMLReaderFactory JavaDoc;
27 import org.xml.sax.helpers.XMLFilterImpl JavaDoc;
28 import org.xml.sax.XMLReader JavaDoc;
29 import org.xml.sax.XMLFilter JavaDoc;
30 import org.xml.sax.ContentHandler JavaDoc;
31 import org.xml.sax.ext.LexicalHandler JavaDoc;
32 import org.xml.sax.ext.DeclHandler JavaDoc;
33
34 // Needed DOM classes
35
import org.w3c.dom.Node JavaDoc;
36 import org.w3c.dom.Document JavaDoc;
37 import org.w3c.dom.Element JavaDoc;
38
39 // Needed JAXP classes
40
import javax.xml.parsers.DocumentBuilder JavaDoc;
41 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
42 import javax.xml.parsers.ParserConfigurationException JavaDoc;
43
44 import java.io.BufferedInputStream JavaDoc; // dml
45

46 import java.net.URL JavaDoc;
47 import java.net.MalformedURLException JavaDoc;
48
49
50 /**
51  * Some examples to show how the Simple API for Transformations
52  * could be used.
53  *
54  * @author <a HREF="mailto:scott_boag@lotus.com">Scott Boag</a>
55  */

56 public class TraxExamples {
57
58     /**
59      * Method main
60      */

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

72         String JavaDoc test = "all";
73         if (argv.length > 0) {
74             test = argv[0];
75         }
76
77         String JavaDoc foo_xml = "xml/foo.xml";
78         String JavaDoc foo_xsl = "xsl/foo.xsl";
79         String JavaDoc baz_xml = "xml/baz.xml";
80         String JavaDoc baz_xsl = "xsl/baz.xsl";
81         String JavaDoc foo2_xsl = "xsl/foo2.xsl";
82         String JavaDoc foo3_xsl = "xsl/foo3.xsl";
83         String JavaDoc text_xsl = "xsl/text.xsl";
84         String JavaDoc embedded_xml = "xml/embedded.xml";
85
86         if (test.equals("all") || test.equals("exampleParseOnly")) {
87             System.out.println("\n\n==== exampleParseOnly ====");
88     
89             try {
90                 exampleParseOnly(foo_xml);
91             } catch (Exception JavaDoc ex) {
92                 handleException(ex);
93             }
94         }
95         
96         
97
98         if (test.equals("all") || test.equals("exampleSimple1")) {
99             System.out.println("\n\n==== exampleSimple1 ====");
100     
101             try {
102                 exampleSimple1(foo_xml, foo_xsl);
103             } catch (Exception JavaDoc ex) {
104                 handleException(ex);
105             }
106         }
107
108         if (test.equals("all") || test.equals("exampleSimple2")) {
109             System.out.println("\n\n==== exampleSimple2 ====");
110     
111             try {
112                 exampleSimple2(foo_xml, foo_xsl);
113             } catch (Exception JavaDoc ex) {
114                 handleException(ex);
115             }
116         }
117
118         if (test.equals("all") || test.equals("exampleFromStream")) {
119             System.out.println("\n\n==== exampleFromStream ====");
120     
121             try {
122                 exampleFromStream(foo_xml, baz_xsl);
123             } catch (Exception JavaDoc ex) {
124                 handleException(ex);
125             }
126         }
127
128         if (test.equals("all") || test.equals("exampleFromReader")) {
129             System.out.println("\n\n==== exampleFromReader ====");
130     
131             try {
132                 exampleFromReader(foo_xml, foo_xsl);
133             } catch (Exception JavaDoc ex) {
134                 handleException(ex);
135             }
136         }
137
138         if (test.equals("all") || test.equals("exampleUseTemplatesObj")) {
139             System.out.println("\n\n==== exampleUseTemplatesObj ====");
140     
141             try {
142                 exampleUseTemplatesObj(foo_xml, baz_xml,
143                                        foo_xsl);
144             } catch (Exception JavaDoc ex) {
145                 handleException(ex);
146             }
147         }
148
149         if (test.equals("all") || test.equals("exampleUseTemplatesHandler")) {
150             System.out.println("\n\n==== exampleUseTemplatesHandler ====");
151     
152             try {
153                 (new TraxExamples()).exampleUseTemplatesHandler(foo_xml, foo_xsl);
154             } catch (Exception JavaDoc ex) {
155                 handleException(ex);
156             }
157         }
158
159         if (test.equals("all") || test.equals("exampleContentHandlerToContentHandler")) {
160             System.out
161             .println("\n\n==== exampleContentHandlerToContentHandler ====");
162
163             try {
164                 exampleContentHandlerToContentHandler(foo_xml,
165                                                       foo_xsl);
166             } catch (Exception JavaDoc ex) {
167                 handleException(ex);
168             }
169         }
170
171         if (test.equals("all") || test.equals("exampleXMLReader")) {
172             System.out.println("\n\n==== exampleXMLReader ====");
173     
174             try {
175                 exampleXMLReader(foo_xml, foo_xsl);
176             } catch (Exception JavaDoc ex) {
177                 handleException(ex);
178             }
179         }
180
181         if (test.equals("all") || test.equals("exampleXMLFilter")) {
182             System.out.println("\n\n==== exampleXMLFilter ====");
183     
184             try {
185                 exampleXMLFilter(foo_xml, foo_xsl);
186             } catch (Exception JavaDoc ex) {
187                 handleException(ex);
188             }
189         }
190
191         if (test.equals("all") || test.equals("exampleXMLFilterChain")) {
192             System.out.println("\n\n==== exampleXMLFilterChain ====");
193     
194             try {
195                 exampleXMLFilterChain(foo_xml, foo_xsl,
196                                       foo2_xsl, foo3_xsl);
197             } catch (Exception JavaDoc ex) {
198                 handleException(ex);
199             }
200         }
201
202         if (test.equals("all") || test.equals("exampleDOMtoDOM")) {
203             System.out.println("\n\n==== exampleDOMtoDOM ====");
204     
205             try {
206                 exampleDOMtoDOM(foo_xml, foo_xsl);
207             } catch (Exception JavaDoc ex) {
208                 handleException(ex);
209             }
210         }
211
212         if (test.equals("all") || test.equals("exampleDOMtoDOMNew")) {
213             System.out.println("\n\n==== exampleDOMtoDOMNew ====");
214     
215             try {
216                 exampleDOMtoDOMNew(foo_xml, foo_xsl);
217             } catch (Exception JavaDoc ex) {
218                 handleException(ex);
219             }
220         }
221
222         if (test.equals("all") || test.equals("exampleDOMtoDOMNonRoot")) {
223             System.out.println("\n\n==== exampleDOMtoDOMNonRoot ====");
224     
225             try {
226                 exampleDOMtoDOMNonRoot(foo_xml, foo_xsl);
227             } catch (Exception JavaDoc ex) {
228                 handleException(ex);
229             }
230         }
231
232         if (test.equals("all") || test.equals("exampleDOMtoDOMAlien")) {
233             System.out.println("\n\n==== exampleDOMtoDOMAlien ====");
234     
235             try {
236                 exampleDOMtoDOMAlien(foo_xml, foo_xsl);
237             } catch (Exception JavaDoc ex) {
238                 handleException(ex);
239             }
240         }
241         
242         if (test.equals("all") || test.equals("exampleNodeInfo")) {
243             System.out.println("\n\n==== exampleNodeInfo ====");
244     
245             try {
246                 exampleNodeInfo(foo_xml, foo_xsl);
247             } catch (Exception JavaDoc ex) {
248                 handleException(ex);
249             }
250         }
251
252         if (test.equals("all") || test.equals("exampleSAXtoDOMNewIdentity")) {
253             System.out.println("\n\n==== exampleSAXtoDOMNewIdentity ====");
254     
255             try {
256                 exampleSAXtoDOMNewIdentity(foo_xml, foo_xsl);
257             } catch (Exception JavaDoc ex) {
258                 handleException(ex);
259             }
260         }
261
262         if (test.equals("all") || test.equals("exampleParam")) {
263             System.out.println("\n\n==== exampleParam ====");
264     
265             try {
266                 exampleParam(foo_xml, foo_xsl);
267             } catch (Exception JavaDoc ex) {
268                 handleException(ex);
269             }
270         }
271
272         if (test.equals("all") || test.equals("exampleTransformerReuse")) {
273             System.out.println("\n\n==== exampleTransformerReuse ====");
274     
275             try {
276                 exampleTransformerReuse(foo_xml, foo_xsl);
277             } catch (Exception JavaDoc ex) {
278                 handleException(ex);
279             }
280         }
281
282         if (test.equals("all") || test.equals("exampleOutputProperties")) {
283             System.out.println("\n\n==== exampleOutputProperties ====");
284     
285             try {
286                 exampleOutputProperties(foo_xml, foo_xsl);
287             } catch (Exception JavaDoc ex) {
288                 handleException(ex);
289             }
290         }
291
292         if (test.equals("all") || test.equals("exampleUseAssociated")) {
293             System.out.println("\n\n==== exampleUseAssociated ====");
294     
295             try {
296                 exampleUseAssociated(foo_xml);
297             } catch (Exception JavaDoc ex) {
298                 handleException(ex);
299             }
300         }
301
302         if (test.equals("all") || test.equals("exampleUseEmbedded")) {
303             System.out.println("\n\n==== exampleUseEmbedded ====");
304     
305             try {
306                 exampleUseAssociated(embedded_xml);
307             } catch (Exception JavaDoc ex) {
308                 handleException(ex);
309             }
310         }
311
312         if (test.equals("all") || test.equals("exampleContentHandlertoDOM")) {
313             System.out.println("\n\n==== exampleContentHandlertoDOM ====");
314     
315             try {
316                 exampleContentHandlertoDOM(foo_xml, foo_xsl);
317             } catch (Exception JavaDoc ex) {
318                 handleException(ex);
319             }
320         }
321
322         if (test.equals("all") || test.equals("exampleAsSerializer")) {
323             System.out.println("\n\n==== exampleAsSerializer ====");
324     
325             try {
326                 exampleAsSerializer(foo_xml, foo_xsl);
327             } catch (Exception JavaDoc ex) {
328                 handleException(ex);
329             }
330         }
331
332         if (test.equals("all") || test.equals("exampleUsingURIResolver")) {
333             System.out.println("\n\n==== exampleUsingURIResolver ====");
334     
335             try {
336                 exampleUsingURIResolver(foo_xml, text_xsl);
337             } catch (Exception JavaDoc ex) {
338                 handleException(ex);
339             }
340         }
341
342         System.out.println("\n==== done! ====");
343     }
344
345     /**
346      * Show the simplest possible transformation from system id
347      * to output stream.
348      */

349     public static void exampleSimple1(String JavaDoc sourceID, String JavaDoc xslID)
350             throws TransformerException, TransformerConfigurationException {
351
352         // Create a transform factory instance.
353
TransformerFactory tfactory = TransformerFactory.newInstance();
354
355         // Create a transformer for the stylesheet.
356
Transformer transformer =
357             tfactory.newTransformer(new StreamSource(xslID));
358
359         // Transform the source XML to System.out.
360
transformer.transform(new StreamSource(sourceID),
361                               new StreamResult(System.out));
362     }
363
364     /**
365      * Example that shows XML parsing only (no transformation)
366      */

367      
368     public static void exampleParseOnly(String JavaDoc sourceID) throws Exception JavaDoc {
369         System.setProperty("javax.xml.parsers.SAXParserFactory",
370                 "com.icl.saxon.aelfred.SAXParserFactoryImpl");
371         SAXParserFactory factory = SAXParserFactory.newInstance();
372         SAXParser parser = factory.newSAXParser();
373         parser.parse(sourceID, new org.xml.sax.helpers.DefaultHandler JavaDoc());
374         System.out.println("\nParsing complete\n");
375     }
376
377     /**
378      * Show the simplest possible transformation from File
379      * to a File.
380      */

381     public static void exampleSimple2(String JavaDoc sourceID, String JavaDoc xslID)
382             throws TransformerException, TransformerConfigurationException {
383
384         // Create a transform factory instance.
385
TransformerFactory tfactory = TransformerFactory.newInstance();
386
387         // Create a transformer for the stylesheet.
388
Transformer transformer =
389             tfactory.newTransformer(new StreamSource(xslID));
390
391         // Transform the source XML to System.out.
392
transformer.transform(new StreamSource(sourceID),
393                               new StreamResult(new File JavaDoc("exampleSimple2.out")));
394                               
395         System.out.println("\nOutput written to exampleSimple2.out\n");
396     }
397
398     /**
399      * Show simple transformation from input stream to output stream.
400      */

401     public static void exampleFromStream(String JavaDoc sourceID, String JavaDoc xslID)
402             throws TransformerException, TransformerConfigurationException,
403                    FileNotFoundException JavaDoc, MalformedURLException JavaDoc {
404
405         // Create a transform factory instance.
406
TransformerFactory tfactory = TransformerFactory.newInstance();
407         InputStream JavaDoc xslIS =
408             new BufferedInputStream JavaDoc(new FileInputStream JavaDoc(xslID));
409         StreamSource xslSource = new StreamSource(xslIS);
410
411         // The following line would be necessary if the stylesheet contained
412
// an xsl:include or xsl:import with a relative URL
413
// xslSource.setSystemId(xslID);
414

415         // Create a transformer for the stylesheet.
416
Transformer transformer = tfactory.newTransformer(xslSource);
417         InputStream JavaDoc xmlIS =
418             new BufferedInputStream JavaDoc(new FileInputStream JavaDoc(sourceID));
419         StreamSource xmlSource = new StreamSource(xmlIS);
420
421         // The following line would be necessary if the source document contained
422
// a call on the document() function using a relative URL
423
// xmlSource.setSystemId(sourceID);
424

425         // Transform the source XML to System.out.
426
transformer.transform(xmlSource, new StreamResult(System.out));
427     }
428
429     /**
430      * Show simple transformation from reader to output stream. In general
431      * this use case is discouraged, since the XML encoding can not be
432      * processed.
433      */

434     public static void exampleFromReader(String JavaDoc sourceID, String JavaDoc xslID)
435             throws TransformerException, TransformerConfigurationException,
436                    FileNotFoundException JavaDoc, MalformedURLException JavaDoc {
437
438         // Create a transform factory instance.
439
TransformerFactory tfactory = TransformerFactory.newInstance();
440
441         // Note that in this case the XML encoding can not be processed!
442
Reader JavaDoc xslReader = new BufferedReader JavaDoc(new FileReader JavaDoc(xslID));
443         StreamSource xslSource = new StreamSource(xslReader);
444
445         // Note that if we don't do this, relative URLs can not be resolved correctly!
446
xslSource.setSystemId(xslID);
447
448         // Create a transformer for the stylesheet.
449
Transformer transformer = tfactory.newTransformer(xslSource);
450
451         // Note that in this case the XML encoding can not be processed!
452
Reader JavaDoc xmlReader = new BufferedReader JavaDoc(new FileReader JavaDoc(sourceID));
453         StreamSource xmlSource = new StreamSource(xmlReader);
454
455         // The following line would be needed if the source document contained
456
// a relative URL
457
// xmlSource.setSystemId(sourceID);
458

459         // Transform the source XML to System.out.
460
transformer.transform(xmlSource, new StreamResult(System.out));
461     }
462
463     /**
464      * Perform a transformation using a compiled stylesheet (a Templates object)
465      */

466     public static void exampleUseTemplatesObj(
467             String JavaDoc sourceID1, String JavaDoc sourceID2, String JavaDoc xslID)
468                 throws TransformerException,
469                        TransformerConfigurationException {
470
471         TransformerFactory tfactory = TransformerFactory.newInstance();
472
473         // Create a templates object, which is the processed,
474
// thread-safe representation of the stylesheet.
475
Templates templates = tfactory.newTemplates(new StreamSource(xslID));
476
477         // Illustrate the fact that you can make multiple transformers
478
// from the same template.
479
Transformer transformer1 = templates.newTransformer();
480         Transformer transformer2 = templates.newTransformer();
481
482         System.out.println("\n\n----- transform of " + sourceID1 + " -----");
483         transformer1.transform(new StreamSource(sourceID1),
484                                new StreamResult(System.out));
485         System.out.println("\n\n----- transform of " + sourceID2 + " -----");
486         transformer2.transform(new StreamSource(sourceID2),
487                                new StreamResult(System.out));
488     }
489
490     /**
491      * Perform a transformation using a compiled stylesheet (a Templates object)
492      */

493     public void exampleUseTemplatesHandler(
494             String JavaDoc sourceID, String JavaDoc xslID)
495                 throws Exception JavaDoc {
496
497         TransformerFactory tfactory = TransformerFactory.newInstance();
498
499         // Does this factory support SAX features?
500
if (tfactory.getFeature(SAXSource.FEATURE)) {
501
502             // If so, we can safely cast.
503
SAXTransformerFactory stfactory =
504                 ((SAXTransformerFactory) tfactory);
505
506             // Create a Templates ContentHandler to handle parsing of the
507
// stylesheet.
508
javax.xml.transform.sax.TemplatesHandler JavaDoc templatesHandler =
509                                stfactory.newTemplatesHandler();
510
511             // Create an XMLReader and set its features.
512
XMLReader JavaDoc reader = makeXMLReader();
513             reader.setFeature("http://xml.org/sax/features/namespaces", true);
514             reader.setFeature("http://xml.org/sax/features/namespace-prefixes", false);
515
516             // Create a XMLFilter that modifies the stylesheet
517
XMLFilter JavaDoc filter = new ModifyStylesheetFilter();
518             filter.setParent(reader);
519
520             filter.setContentHandler(templatesHandler);
521
522             // Parse the stylesheet.
523
filter.parse(new InputSource JavaDoc(xslID));
524
525             // Get the Templates object (generated during the parsing of the stylesheet)
526
// from the TemplatesHandler.
527
Templates templates = templatesHandler.getTemplates();
528             
529             // do the transformation
530
templates.newTransformer().transform(
531                     new StreamSource(sourceID), new StreamResult(System.out));
532                     
533         } else {
534             System.out.println("Factory doesn't implement SAXTransformerFactory");
535         }
536
537     }
538     
539     private class ModifyStylesheetFilter extends XMLFilterImpl JavaDoc {
540         public void startDocument () throws SAXException JavaDoc {
541             System.err.println("ModifyStylesheetFilter#startDocument");
542             super.startDocument();
543         }
544         public void startElement (String JavaDoc namespaceURI, String JavaDoc localName,
545                           String JavaDoc qName, Attributes JavaDoc atts) throws SAXException JavaDoc {
546             String JavaDoc lname = (qName.startsWith("xsl:") ? localName : ("XX" + localName));
547             super.startElement(namespaceURI, lname, qName, atts);
548         }
549         public void endElement (String JavaDoc namespaceURI, String JavaDoc localName,
550                           String JavaDoc qName) throws SAXException JavaDoc {
551             String JavaDoc lname = (qName.startsWith("xsl:") ? localName : ("XX" + localName));
552             super.endElement(namespaceURI, lname, qName);
553         }
554     }
555
556     /**
557      * Show the Transformer using SAX events in and SAX events out.
558      */

559     public static void exampleContentHandlerToContentHandler(
560             String JavaDoc sourceID, String JavaDoc xslID)
561                 throws TransformerException,
562                        TransformerConfigurationException, SAXException JavaDoc,
563                        IOException JavaDoc, MalformedURLException JavaDoc {
564
565         TransformerFactory tfactory = TransformerFactory.newInstance();
566
567         // Does this factory support SAX features?
568
if (tfactory.getFeature(SAXSource.FEATURE)) {
569
570             // If so, we can safely cast.
571
SAXTransformerFactory stfactory =
572                 ((SAXTransformerFactory) tfactory);
573
574             // A TransformerHandler is a ContentHandler that will listen for
575
// SAX events, and transform them to the result.
576
TransformerHandler handler =
577                 stfactory.newTransformerHandler(new StreamSource(xslID));
578
579             // Set the result handling to be a serialization to System.out.
580
Result result = new SAXResult(new ExampleContentHandler());
581
582             handler.setResult(result);
583
584             // Create a reader, and set it's content handler to be the TransformerHandler.
585
XMLReader JavaDoc reader = makeXMLReader();
586
587             reader.setContentHandler(handler);
588
589             // It's a good idea for the parser to send lexical events.
590
// The TransformerHandler is also a LexicalHandler.
591
reader.setProperty(
592                 "http://xml.org/sax/properties/lexical-handler", handler);
593
594             // Parse the source XML, and send the parse events to the TransformerHandler.
595
reader.parse(sourceID);
596         } else {
597             System.out.println(
598                 "Can't do exampleContentHandlerToContentHandler because tfactory is not a SAXTransformerFactory");
599         }
600     }
601
602     /**
603      * Show the Transformer as a SAX2 XMLReader. An XMLFilter obtained
604      * from newXMLFilter should act as a transforming XMLReader if setParent is not
605      * called. Internally, an XMLReader is created as the parent for the XMLFilter.
606      */

607     public static void exampleXMLReader(String JavaDoc sourceID, String JavaDoc xslID)
608             throws TransformerException, TransformerConfigurationException,
609                    SAXException JavaDoc, IOException JavaDoc, MalformedURLException JavaDoc
610                        // , ParserConfigurationException
611
{
612
613         TransformerFactory tfactory = TransformerFactory.newInstance();
614
615         if (tfactory.getFeature(SAXSource.FEATURE)) {
616             XMLReader JavaDoc reader =
617                 ((SAXTransformerFactory) tfactory)
618                     .newXMLFilter(new StreamSource(new File JavaDoc(xslID)));
619
620             reader.setContentHandler(new ExampleContentHandler());
621             reader.parse(new InputSource JavaDoc(new File JavaDoc(sourceID).toURL().toString()));
622         } else {
623             System.out.println("tfactory does not support SAX features!");
624         }
625     }
626
627     /**
628      * Show the Transformer as a simple XMLFilter. This is pretty similar
629      * to exampleXMLReader, except that here the parent XMLReader is created
630      * by the caller, instead of automatically within the XMLFilter. This
631      * gives the caller more direct control over the parent reader.
632      */

633     public static void exampleXMLFilter(String JavaDoc sourceID, String JavaDoc xslID)
634             throws TransformerException, TransformerConfigurationException,
635                    SAXException JavaDoc, IOException JavaDoc, MalformedURLException JavaDoc
636                        // , ParserConfigurationException
637
{
638
639         TransformerFactory tfactory = TransformerFactory.newInstance();
640         XMLReader JavaDoc reader = makeXMLReader();
641
642
643         // The transformer will use a SAX parser as it's reader.
644
// LOOKS WRONG: should be set on filter, see below!
645
// reader.setContentHandler(new ExampleContentHandler());
646

647         try {
648             reader.setFeature(
649                 "http://xml.org/sax/features/namespace-prefixes", true);
650             reader.setFeature(
651                 "http://apache.org/xml/features/validation/dynamic", true);
652         } catch (SAXException JavaDoc se) {
653
654             // What can we do?
655
// TODO: User diagnostics.
656
}
657
658         XMLFilter JavaDoc filter =
659             ((SAXTransformerFactory) tfactory)
660                 .newXMLFilter(new StreamSource(new File JavaDoc(xslID)));
661
662         filter.setParent(reader);
663         filter.setContentHandler(new ExampleContentHandler());
664
665         // Now, when you call transformer.parse, it will set itself as
666
// the content handler for the parser object (it's "parent"), and
667
// will then call the parse method on the parser.
668
filter.parse(new InputSource JavaDoc(new File JavaDoc(sourceID).toURL().toString()));
669     }
670
671     /**
672      * This example shows how to chain events from one Transformer
673      * to another transformer, using the Transformer as a
674      * SAX2 XMLFilter/XMLReader.
675      */

676     public static void exampleXMLFilterChain(
677             String JavaDoc sourceID, String JavaDoc xslID_1, String JavaDoc xslID_2, String JavaDoc xslID_3)
678                 throws TransformerException,
679                        TransformerConfigurationException, SAXException JavaDoc,
680                        IOException JavaDoc, MalformedURLException JavaDoc {
681
682         TransformerFactory tfactory = TransformerFactory.newInstance();
683         Templates stylesheet1 =
684             tfactory.newTemplates(new StreamSource(new File JavaDoc(xslID_1)));
685         Transformer transformer1 = stylesheet1.newTransformer();
686
687         // If one success, assume all will succeed.
688
if (tfactory.getFeature(SAXSource.FEATURE)) {
689             SAXTransformerFactory stf = (SAXTransformerFactory) tfactory;
690             XMLReader JavaDoc reader = makeXMLReader();
691
692             XMLFilter JavaDoc filter1 = stf.newXMLFilter(new StreamSource(new File JavaDoc(xslID_1)));
693             XMLFilter JavaDoc filter2 = stf.newXMLFilter(new StreamSource(new File JavaDoc(xslID_2)));
694             XMLFilter JavaDoc filter3 = stf.newXMLFilter(new StreamSource(new File JavaDoc(xslID_3)));
695
696             if (null != filter1) // If one success, assume all were success.
697
{
698
699                 // transformer1 will use a SAX parser as it's reader.
700
filter1.setParent(reader);
701
702                 // transformer2 will use transformer1 as it's reader.
703
filter2.setParent(filter1);
704
705                 // transformer3 will use transformer2 as it's reader.
706
filter3.setParent(filter2);
707                 filter3.setContentHandler(new ExampleContentHandler());
708
709                 // filter3.setContentHandler(new org.xml.sax.helpers.DefaultHandler());
710
// Now, when you call transformer3 to parse, it will set
711
// itself as the ContentHandler for transform2, and
712
// call transform2.parse, which will set itself as the
713
// content handler for transform1, and call transform1.parse,
714
// which will set itself as the content listener for the
715
// SAX parser, and call parser.parse(new InputSource(foo_xml)).
716
filter3.parse(new InputSource JavaDoc(new File JavaDoc(sourceID).toURL().toString()));
717             } else {
718                 System.out
719                     .println("Can't do exampleXMLFilter because "
720                              + "tfactory doesn't support newXMLFilter()");
721             }
722         } else {
723             System.out.println("Can't do exampleXMLFilter because "
724                                + "tfactory is not a SAXTransformerFactory");
725         }
726     }
727
728     /**
729      * Show how to transform a DOM tree into another DOM tree.
730      * This uses the javax.xml.parsers to parse an XML file into a
731      * DOM, and create an output DOM.
732      */

733     public static Node JavaDoc exampleDOMtoDOM(String JavaDoc sourceID, String JavaDoc xslID)
734             throws TransformerException, TransformerConfigurationException,
735                    SAXException JavaDoc, IOException JavaDoc, ParserConfigurationException JavaDoc,
736                    MalformedURLException JavaDoc {
737
738         TransformerFactory tfactory = TransformerFactory.newInstance();
739
740         if (tfactory.getFeature(DOMSource.FEATURE)) {
741             Templates templates;
742
743             {
744                 System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
745                      "com.icl.saxon.om.DocumentBuilderFactoryImpl");
746                 DocumentBuilderFactory JavaDoc dfactory =
747                     DocumentBuilderFactory.newInstance();
748                     System.err.println("Using DocumentBuilderFactory " + dfactory.getClass());
749
750                 dfactory.setNamespaceAware(true);
751
752                 DocumentBuilder JavaDoc docBuilder =
753                     dfactory.newDocumentBuilder();
754                     System.err.println("Using DocumentBuilder " + docBuilder.getClass());
755                 org.w3c.dom.Document JavaDoc outNode = docBuilder.newDocument();
756                 
757                 Node JavaDoc doc =
758                     docBuilder.parse(new InputSource JavaDoc(new File JavaDoc(xslID).toURL().toString()));
759                 System.err.println("Stylesheet document built OK");
760                 DOMSource dsource = new DOMSource(doc);
761
762                 // If we don't do this, the transformer won't know how to
763
// resolve relative URLs in the stylesheet.
764
dsource.setSystemId(new File JavaDoc(xslID).toURL().toString());
765
766                 templates = tfactory.newTemplates(dsource);
767             }
768
769             Transformer transformer = templates.newTransformer();
770             DocumentBuilderFactory JavaDoc dfactory = DocumentBuilderFactory.newInstance();
771             DocumentBuilder JavaDoc docBuilder = dfactory.newDocumentBuilder();
772             org.w3c.dom.Document JavaDoc outNode = docBuilder.newDocument();
773             Node JavaDoc doc = docBuilder.parse(
774                           new InputSource JavaDoc(new File JavaDoc(sourceID).toURL().toString()));
775
776             System.err.println("Source document built OK");
777             
778             // added by MHK
779
DOMSource ds = new DOMSource(doc);
780             ds.setSystemId(new File JavaDoc(sourceID).toURL().toString());
781             // end of addition
782
transformer.transform(ds, new DOMResult(outNode));
783             System.err.println("Transformation done OK");
784             
785             // Serialize the output so we can see the transformation actually worked
786
Transformer serializer = tfactory.newTransformer();
787
788             serializer.transform(new DOMSource(outNode),
789                                  new StreamResult(System.out));
790
791             return outNode;
792         } else {
793             throw new org.xml.sax.SAXNotSupportedException JavaDoc(
794                 "DOM node processing not supported!");
795         }
796     }
797
798     /**
799      * Show how to transform a DOM tree into another DOM tree.
800      * This uses the javax.xml.parsers to parse an XML file into the source
801      * DOM; it leaves the XSLT processor to create the result DOM.
802      */

803     public static void exampleDOMtoDOMNew(String JavaDoc sourceID, String JavaDoc xslID)
804             throws TransformerException, TransformerConfigurationException,
805                    SAXException JavaDoc, IOException JavaDoc, ParserConfigurationException JavaDoc,
806                    MalformedURLException JavaDoc {
807
808         TransformerFactory tfactory = TransformerFactory.newInstance();
809
810         if (tfactory.getFeature(DOMSource.FEATURE)) {
811             Templates templates;
812
813             {
814                 System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
815                      "com.icl.saxon.om.DocumentBuilderFactoryImpl");
816                 DocumentBuilderFactory JavaDoc dfactory =
817                     DocumentBuilderFactory.newInstance();
818                     System.err.println("Using DocumentBuilderFactory " + dfactory.getClass());
819
820                 dfactory.setNamespaceAware(true);
821
822                 DocumentBuilder JavaDoc docBuilder =
823                     dfactory.newDocumentBuilder();
824                     System.err.println("Using DocumentBuilder " + docBuilder.getClass());
825                 org.w3c.dom.Document JavaDoc outNode = docBuilder.newDocument();
826                 
827                 Node JavaDoc doc =
828                     docBuilder.parse(new InputSource JavaDoc(new File JavaDoc(xslID).toURL().toString()));
829                 System.err.println("Stylesheet document built OK");
830                 DOMSource dsource = new DOMSource(doc);
831
832                 // If we don't do this, the transformer won't know how to
833
// resolve relative URLs in the stylesheet.
834
dsource.setSystemId(new File JavaDoc(xslID).toURL().toString());
835
836                 templates = tfactory.newTemplates(dsource);
837             }
838
839             Transformer transformer = templates.newTransformer();
840             DocumentBuilderFactory JavaDoc dfactory = DocumentBuilderFactory.newInstance();
841             DocumentBuilder JavaDoc docBuilder = dfactory.newDocumentBuilder();
842             //org.w3c.dom.Document outNode = docBuilder.newDocument();
843
Node JavaDoc doc = docBuilder.parse(
844                           new InputSource JavaDoc(new File JavaDoc(sourceID).toURL().toString()));
845
846             System.err.println("Source document built OK");
847             
848             // added by MHK
849
DOMSource ds = new DOMSource(doc);
850             //ds.setSystemId(new File(sourceID).toURL().toString());
851
// end of addition
852
DOMResult result = new DOMResult();
853             transformer.transform(ds, result);
854             System.err.println("Transformation done OK");
855             
856             // Serialize the output so we can see the transformation actually worked
857
Transformer serializer = tfactory.newTransformer();
858
859             serializer.transform(new DOMSource(result.getNode()),
860                                  new StreamResult(System.out));
861                                  
862             int k = result.getNode().getChildNodes().getLength();
863             System.err.println("Result root has " + k + " children");
864
865         } else {
866             throw new org.xml.sax.SAXNotSupportedException JavaDoc(
867                 "DOM node processing not supported!");
868         }
869     }
870
871     /**
872      * Show how to transform a DOM tree into another DOM tree.
873      * This uses the javax.xml.parsers to parse an XML file into a
874      * DOM, and create an output DOM. In this example, the start node
875      * for the transformation is an element, not the root node.
876      */

877     public static Node JavaDoc exampleDOMtoDOMNonRoot(String JavaDoc sourceID, String JavaDoc xslID)
878             throws TransformerException, TransformerConfigurationException,
879                    SAXException JavaDoc, IOException JavaDoc, ParserConfigurationException JavaDoc,
880                    MalformedURLException JavaDoc {
881
882         TransformerFactory tfactory = TransformerFactory.newInstance();
883
884         if (tfactory.getFeature(DOMSource.FEATURE)) {
885             Templates templates;
886
887             {
888                 System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
889                      "com.icl.saxon.om.DocumentBuilderFactoryImpl");
890                      
891                 DocumentBuilderFactory JavaDoc dfactory = DocumentBuilderFactory.newInstance();
892                     System.err.println("Using DocumentBuilderFactory " + dfactory.getClass());
893
894                 dfactory.setNamespaceAware(true);
895
896                 DocumentBuilder JavaDoc docBuilder = dfactory.newDocumentBuilder();
897                     System.err.println("Using DocumentBuilder " + docBuilder.getClass());
898                 org.w3c.dom.Document JavaDoc outNode = docBuilder.newDocument();
899                 
900                 Node JavaDoc doc =
901                     docBuilder.parse(new InputSource JavaDoc(new File JavaDoc(xslID).toURL().toString()));
902                 System.err.println("Stylesheet document built OK");
903                 DOMSource dsource = new DOMSource(doc);
904
905                 // If we don't do this, the transformer won't know how to
906
// resolve relative URLs in the stylesheet.
907
dsource.setSystemId(new File JavaDoc(xslID).toURL().toString());
908
909                 templates = tfactory.newTemplates(dsource);
910             }
911
912             Transformer transformer = templates.newTransformer();
913             DocumentBuilderFactory JavaDoc dfactory = DocumentBuilderFactory.newInstance();
914             DocumentBuilder JavaDoc docBuilder = dfactory.newDocumentBuilder();
915             Document JavaDoc outNode = docBuilder.newDocument();
916             Document JavaDoc doc = docBuilder.parse(
917                           new InputSource JavaDoc(new File JavaDoc(sourceID).toURL().toString()));
918             Node JavaDoc bar = doc.getDocumentElement().getFirstChild();
919             while (bar.getNodeType() != Node.ELEMENT_NODE) {
920                 bar = bar.getNextSibling();
921             }
922
923             System.err.println("Source document built OK");
924             
925             // added by MHK
926
DOMSource ds = new DOMSource(bar);
927             ds.setSystemId(new File JavaDoc(sourceID).toURL().toString());
928             // end of addition
929
transformer.transform(ds, new DOMResult(outNode));
930             System.err.println("Transformation done OK");
931             
932             // Serialize the output so we can see the transformation actually worked
933
Transformer serializer = tfactory.newTransformer();
934
935             serializer.transform(new DOMSource(outNode),
936                                  new StreamResult(System.out));
937
938             return outNode;
939         } else {
940             throw new org.xml.sax.SAXNotSupportedException JavaDoc(
941                 "DOM node processing not supported!");
942         }
943     }
944
945
946     /**
947      * Show how to transform a DOM tree into another DOM tree.
948      * This uses the javax.xml.parsers to parse an XML file into a
949      * DOM, and create an output DOM. In this example, Saxon uses a
950      * third-party DOM as both input and output.
951      */

952     public static void exampleDOMtoDOMAlien(String JavaDoc sourceID, String JavaDoc xslID)
953             throws TransformerException, TransformerConfigurationException,
954                    SAXException JavaDoc, IOException JavaDoc, ParserConfigurationException JavaDoc,
955                    MalformedURLException JavaDoc {
956
957         String JavaDoc factory = null;
958
959         // Try the crimson parser
960
try {
961             Class.forName("org.apache.crimson.jaxp.DocumentBuilderFactoryImpl");
962             factory = "org.apache.crimson.jaxp.DocumentBuilderFactoryImpl";
963         }
964         catch (Exception JavaDoc e) {
965             factory = null;
966         }
967
968         // Try the Xerces parser
969
if (factory==null) {
970             try {
971                 Class.forName("org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
972                 factory = "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl";
973             }
974             catch (Exception JavaDoc e) {
975                 factory = null;
976             }
977         }
978         
979         if (factory==null) {
980             System.err.println("No third-party DOM Builder found");
981             return;
982         }
983         
984         System.setProperty("javax.xml.parsers.DocumentBuilderFactory", factory);
985         
986         TransformerFactory tfactory = TransformerFactory.newInstance();
987
988         if (tfactory.getFeature(DOMSource.FEATURE)) {
989             Templates templates;
990
991             {
992                 DocumentBuilderFactory JavaDoc dfactory = DocumentBuilderFactory.newInstance();
993                     System.err.println("Using DocumentBuilderFactory " + dfactory.getClass());
994
995                 dfactory.setNamespaceAware(true);
996
997                 DocumentBuilder JavaDoc docBuilder = dfactory.newDocumentBuilder();
998                     System.err.println("Using DocumentBuilder " + docBuilder.getClass());
999                 org.w3c.dom.Document JavaDoc outNode = docBuilder.newDocument();
1000                
1001                Node JavaDoc doc =
1002                    docBuilder.parse(new InputSource JavaDoc(new File JavaDoc(xslID).toURL().toString()));
1003                System.err.println("Stylesheet document built OK");
1004                DOMSource dsource = new DOMSource(doc);
1005
1006                // If we don't do this, the transformer won't know how to
1007
// resolve relative URLs in the stylesheet.
1008
dsource.setSystemId(new File JavaDoc(xslID).toURL().toString());
1009
1010                templates = tfactory.newTemplates(dsource);
1011            }
1012
1013            Transformer transformer = templates.newTransformer();
1014            DocumentBuilderFactory JavaDoc dfactory = DocumentBuilderFactory.newInstance();
1015            DocumentBuilder JavaDoc docBuilder = dfactory.newDocumentBuilder();
1016
1017            Document JavaDoc doc = docBuilder.parse(
1018                          new InputSource JavaDoc(new File JavaDoc(sourceID).toURL().toString()));
1019            Node JavaDoc bar = doc.getDocumentElement().getFirstChild();
1020            while (bar.getNodeType() != Node.ELEMENT_NODE) {
1021                bar = bar.getNextSibling();
1022            }
1023
1024            System.err.println("Source document built OK");
1025            
1026            // added by MHK
1027
DOMSource ds = new DOMSource(bar);
1028            ds.setSystemId(new File JavaDoc(sourceID).toURL().toString());
1029            // end of addition
1030

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

1034            Document JavaDoc out = docBuilder.newDocument();
1035            Element JavaDoc extra = out.createElement("extra");
1036            out.appendChild(extra);
1037
1038
1039            transformer.transform(ds, new DOMResult(extra));
1040            System.err.println("Transformation done OK");
1041            
1042            // Serialize the output so we can see the transformation actually worked
1043
Transformer serializer = tfactory.newTransformer();
1044
1045            serializer.transform(new DOMSource(out),
1046                                 new StreamResult(System.out));
1047
1048            return;
1049        } else {
1050            throw new org.xml.sax.SAXNotSupportedException JavaDoc(
1051                "DOM node processing not supported!");
1052        }
1053    }
1054
1055
1056    /**
1057     * Identity transformation from a SAX Source to a new DOM result.
1058     * This leaves the XSLT processor to create the result DOM.
1059     */

1060    public static void exampleSAXtoDOMNewIdentity(String JavaDoc sourceID, String JavaDoc xslID)
1061            throws TransformerException, TransformerConfigurationException,
1062                   SAXException JavaDoc, IOException JavaDoc, ParserConfigurationException JavaDoc,
1063                   MalformedURLException JavaDoc {
1064
1065        TransformerFactory tfactory = TransformerFactory.newInstance();
1066        Transformer transformer = tfactory.newTransformer();
1067        SAXSource source = new SAXSource(new InputSource JavaDoc(sourceID));
1068        DOMResult result = new DOMResult();
1069        transformer.transform(source, result);
1070
1071        System.err.println("Transformation done OK");
1072        
1073        // Serialize the output so we can see the transformation actually worked
1074
Transformer serializer = tfactory.newTransformer();
1075
1076        serializer.transform(new DOMSource(result.getNode()),
1077                             new StreamResult(System.out));
1078                             
1079        int k = result.getNode().getChildNodes().getLength();
1080        System.err.println("Result root has " + k + " children");
1081
1082    }
1083
1084    /**
1085     * Show how to transform directly from a Saxon NodeInfo object.
1086     * This example is peculiar to Saxon: it is not pure JAXP.
1087     */

1088    public static void exampleNodeInfo(String JavaDoc sourceID, String JavaDoc xslID)
1089            throws TransformerException, TransformerConfigurationException,
1090                   SAXException JavaDoc, IOException JavaDoc, ParserConfigurationException JavaDoc,
1091                   MalformedURLException JavaDoc {
1092
1093        TransformerFactory tfactory = TransformerFactory.newInstance();
1094        Templates templates = tfactory.newTemplates(new StreamSource(xslID));
1095        Transformer transformer = templates.newTransformer();
1096        com.icl.saxon.om.Builder builder =
1097            ((com.icl.saxon.Controller)transformer).makeBuilder();
1098        com.icl.saxon.om.DocumentInfo doc =
1099            builder.build(new SAXSource(new InputSource JavaDoc(sourceID)));
1100        transformer.transform(doc, new StreamResult(System.out));
1101    }
1102
1103
1104    /**
1105     * This shows how to set a parameter for use by the templates. Use
1106     * two transformers to show that different parameters may be set
1107     * on different transformers.
1108     */

1109    public static void exampleParam(String JavaDoc sourceID, String JavaDoc xslID)
1110            throws TransformerException, TransformerConfigurationException {
1111
1112        TransformerFactory tfactory = TransformerFactory.newInstance();
1113        Templates templates =
1114            tfactory.newTemplates(new StreamSource(new File JavaDoc(xslID)));
1115        Transformer transformer1 = templates.newTransformer();
1116        Transformer transformer2 = templates.newTransformer();
1117
1118        transformer1.setParameter("a-param", "hello to you!");
1119        transformer1.transform(new StreamSource(new File JavaDoc(sourceID)),
1120                               new StreamResult(System.out));
1121        System.out.println("\n========= (and again with a different parameter value) ===");
1122        transformer1.setParameter("a-param", "goodbye to you!");
1123        transformer1.transform(new StreamSource(new File JavaDoc(sourceID)),
1124                               new StreamResult(System.out));
1125        System.out.println("\n========= (and again with a no parameter value) ===");
1126        transformer2.setOutputProperty(OutputKeys.INDENT, "yes");
1127        transformer2.transform(new StreamSource(new File JavaDoc(sourceID)),
1128                               new StreamResult(System.out));
1129    }
1130
1131    /**
1132     * Show the that a transformer can be reused, and show resetting
1133     * a parameter on the transformer.
1134     */

1135    public static void exampleTransformerReuse(String JavaDoc sourceID, String JavaDoc xslID)
1136            throws TransformerException, TransformerConfigurationException {
1137
1138        // Create a transform factory instance.
1139
TransformerFactory tfactory = TransformerFactory.newInstance();
1140
1141        // Create a transformer for the stylesheet.
1142
Transformer transformer =
1143            tfactory.newTransformer(new StreamSource(new File JavaDoc(xslID)));
1144
1145        transformer.setParameter("a-param", "hello to you!");
1146
1147        // Transform the source XML to System.out.
1148
transformer.transform(new StreamSource(new File JavaDoc(sourceID)),
1149                              new StreamResult(System.out));
1150        System.out.println("\n=========\n");
1151        transformer.setParameter("a-param", "hello to me!");
1152        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
1153
1154        // Transform the source XML to System.out.
1155
transformer.transform(new StreamSource(new File JavaDoc(sourceID)),
1156                              new StreamResult(System.out));
1157    }
1158
1159    /**
1160     * Show how to override output properties.
1161     */

1162    public static void exampleOutputProperties(String JavaDoc sourceID, String JavaDoc xslID)
1163            throws TransformerException, TransformerConfigurationException {
1164
1165        TransformerFactory tfactory = TransformerFactory.newInstance();
1166        Templates templates =
1167            tfactory.newTemplates(new StreamSource(new File JavaDoc(xslID)));
1168        Properties JavaDoc oprops = templates.getOutputProperties();
1169
1170        oprops.put(OutputKeys.INDENT, "yes");
1171
1172        Transformer transformer = templates.newTransformer();
1173
1174        transformer.setOutputProperties(oprops);
1175        transformer.transform(new StreamSource(new File JavaDoc(sourceID)),
1176                              new StreamResult(System.out));
1177    }
1178
1179    /**
1180     * Show how to get stylesheets that are associated with a given
1181     * xml document via the xml-stylesheet PI (see http://www.w3.org/TR/xml-stylesheet/).
1182     */

1183    public static void exampleUseAssociated(String JavaDoc sourceID)
1184            throws TransformerException, TransformerConfigurationException {
1185
1186        TransformerFactory tfactory = TransformerFactory.newInstance();
1187
1188        // The DOM tfactory will have it's own way, based on DOM2,
1189
// of getting associated stylesheets.
1190
if (tfactory instanceof SAXTransformerFactory) {
1191            SAXTransformerFactory stf =
1192                ((SAXTransformerFactory) tfactory);
1193            Source JavaDoc sources =
1194                stf.getAssociatedStylesheet(new StreamSource(sourceID), null,
1195                                            null, null);
1196
1197            if (null != sources) {
1198                Transformer transformer = tfactory.newTransformer(sources);
1199
1200                transformer.transform(new StreamSource(sourceID),
1201                                      new StreamResult(System.out));
1202            } else {
1203                System.out.println("Can't find the associated stylesheet!");
1204            }
1205        }
1206    }
1207
1208    /**
1209     * Show the Transformer using SAX events in and DOM nodes out.
1210     */

1211    public static void exampleContentHandlertoDOM(
1212            String JavaDoc sourceID, String JavaDoc xslID)
1213                throws TransformerException,
1214                       TransformerConfigurationException, SAXException JavaDoc,
1215                       IOException JavaDoc, ParserConfigurationException JavaDoc {
1216
1217        TransformerFactory tfactory = TransformerFactory.newInstance();
1218
1219        // Make sure the transformer factory we obtained supports both
1220
// DOM and SAX.
1221
if (tfactory.getFeature(SAXSource.FEATURE)
1222                && tfactory.getFeature(DOMSource.FEATURE)) {
1223
1224            // We can now safely cast to a SAXTransformerFactory.
1225
SAXTransformerFactory sfactory = (SAXTransformerFactory) tfactory;
1226
1227            // Create an Document node as the root for the output.
1228
DocumentBuilderFactory JavaDoc dfactory =
1229                DocumentBuilderFactory.newInstance();
1230            DocumentBuilder JavaDoc docBuilder = dfactory.newDocumentBuilder();
1231            org.w3c.dom.Document JavaDoc outNode = docBuilder.newDocument();
1232
1233            // Create a ContentHandler that can liston to SAX events
1234
// and transform the output to DOM nodes.
1235
TransformerHandler handler =
1236                sfactory.newTransformerHandler(new StreamSource(xslID));
1237
1238            handler.setResult(new DOMResult(outNode));
1239
1240            // Create a reader and set it's ContentHandler to be the
1241
// transformer.
1242
XMLReader JavaDoc reader = makeXMLReader();
1243
1244            reader.setContentHandler(handler);
1245            reader.setProperty(
1246                "http://xml.org/sax/properties/lexical-handler", handler);
1247
1248            // Send the SAX events from the parser to the transformer,
1249
// and thus to the DOM tree.
1250
reader.parse(sourceID);
1251
1252            // Serialize the node for diagnosis.
1253
exampleSerializeNode(outNode);
1254        } else {
1255            System.out.println(
1256                "Can't do exampleContentHandlerToContentHandler because tfactory is not a SAXTransformerFactory");
1257        }
1258    }
1259
1260    /**
1261     * Show a transformation using a user-written URI Resolver.
1262     */

1263     
1264    public static void exampleUsingURIResolver(String JavaDoc sourceID, String JavaDoc xslID)
1265            throws TransformerException, TransformerConfigurationException {
1266
1267        // Create a transform factory instance.
1268
TransformerFactory tfactory = TransformerFactory.newInstance();
1269
1270        // Create a transformer for the stylesheet.
1271
Transformer transformer =
1272            tfactory.newTransformer(new StreamSource(xslID));
1273            
1274        // Set the URIResolver
1275
transformer.setURIResolver(new UserURIResolver(transformer));
1276
1277        // Transform the source XML to System.out.
1278
transformer.transform(new StreamSource(sourceID),
1279                              new StreamResult(System.out));
1280                              
1281    }
1282
1283    /**
1284    * A sample URIResolver. This handles a URI ending with ".txt". It loads the
1285    * text file identified by the URI, assuming it is in ISO-8859-1 encoding,
1286    * into a tree containing a single text node. It returns this
1287    * result tree to the transformer, exploiting the fact that a Saxon NodeInfo
1288    * can be used as a Source. If the URI doesn't end with ".txt", it hands over
1289    * to the standard URI resolver by returning null.
1290    */

1291    
1292    public static class UserURIResolver implements URIResolver {
1293
1294        Transformer transformer;
1295        public UserURIResolver(Transformer t) {
1296            transformer = t;
1297        }
1298    
1299        /**
1300        * Resolve a URI
1301        * @param baseURI The base URI that should be used. May be null if uri is absolute.
1302        * @params uri The relative or absolute URI. May be an empty string. May contain
1303        * a fragment identifier starting with "#", which must be the value of an ID attribute
1304        * in the referenced XML document.
1305        * @return a Source object representing an XML document
1306        */

1307    
1308        public Source JavaDoc resolve(String JavaDoc href, String JavaDoc base)
1309        throws TransformerException {
1310            if (href.endsWith(".txt")) {
1311                try {
1312                    URL JavaDoc url = new URL JavaDoc(new URL JavaDoc(base), href);
1313                    java.io.InputStream JavaDoc in = url.openConnection().getInputStream();
1314                    java.io.InputStreamReader JavaDoc reader =
1315                        new java.io.InputStreamReader JavaDoc(in, "iso-8859-1");
1316                    
1317                    // this could be vastly more efficient, but it doesn't matter here
1318

1319                    StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
1320                    while (true) {
1321                        int c = reader.read();
1322                        if (c<0) break;
1323                        sb.append((char)c);
1324                    }
1325                    com.icl.saxon.expr.TextFragmentValue tree =
1326                        new com.icl.saxon.expr.TextFragmentValue(
1327                            sb.toString(), url.toString(),
1328                            (com.icl.saxon.Controller)transformer);
1329                    return tree.getFirst();
1330                } catch (Exception JavaDoc err) {
1331                    throw new TransformerException(err);
1332                }
1333            } else {
1334                return null;
1335            }
1336        }
1337        
1338    } // end of inner class UserURIResolver
1339

1340
1341    /**
1342     * Serialize a node to System.out.
1343     */

1344    public static void exampleSerializeNode(Node JavaDoc node)
1345            throws TransformerException, TransformerConfigurationException,
1346                   SAXException JavaDoc, IOException JavaDoc, ParserConfigurationException JavaDoc {
1347
1348        TransformerFactory tfactory = TransformerFactory.newInstance();
1349
1350        // This creates a transformer that does a simple identity transform,
1351
// and thus can be used for all intents and purposes as a serializer.
1352
Transformer serializer = tfactory.newTransformer();
1353
1354        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
1355        serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
1356        serializer.transform(new DOMSource(node),
1357                             new StreamResult(System.out));
1358    }
1359
1360    /**
1361     * A fuller example showing how the TrAX interface can be used
1362     * to serialize a DOM tree.
1363     */

1364    public static void exampleAsSerializer(String JavaDoc sourceID, String JavaDoc xslID)
1365            throws TransformerException, TransformerConfigurationException,
1366                   SAXException JavaDoc, IOException JavaDoc, ParserConfigurationException JavaDoc {
1367
1368        DocumentBuilderFactory JavaDoc dfactory =
1369            DocumentBuilderFactory.newInstance();
1370        DocumentBuilder JavaDoc docBuilder = dfactory.newDocumentBuilder();
1371        org.w3c.dom.Document JavaDoc outNode = docBuilder.newDocument();
1372        Node JavaDoc doc =
1373            docBuilder.parse(new InputSource JavaDoc(sourceID));
1374        TransformerFactory tfactory = TransformerFactory.newInstance();
1375
1376        // This creates a transformer that does a simple identity transform,
1377
// and thus can be used for all intents and purposes as a serializer.
1378
Transformer serializer = tfactory.newTransformer();
1379        Properties JavaDoc oprops = new Properties JavaDoc();
1380
1381        oprops.put("method", "html");
1382        oprops.put("{http://icl.com/saxon}indent-spaces", "2");
1383        serializer.setOutputProperties(oprops);
1384        serializer.transform(new DOMSource(doc),
1385                             new StreamResult(System.out));
1386    }
1387
1388    private static void handleException(Exception JavaDoc ex) {
1389
1390        System.out.println("EXCEPTION: " + ex);
1391        ex.printStackTrace();
1392
1393        if (ex instanceof TransformerConfigurationException) {
1394            System.out.println();
1395            System.out.println("Test failed");
1396
1397            Throwable JavaDoc ex1 =
1398                ((TransformerConfigurationException) ex).getException();
1399                
1400            if (ex1!=null) { // added by MHK
1401
ex1.printStackTrace();
1402    
1403                if (ex1 instanceof SAXException JavaDoc) {
1404                    Exception JavaDoc ex2 = ((SAXException JavaDoc) ex1).getException();
1405    
1406                    System.out.println("Internal sub-exception: ");
1407                    ex2.printStackTrace();
1408                }
1409            }
1410        }
1411    }
1412    
1413    /**
1414    * Make an XMLReader
1415    */

1416    
1417    private static XMLReader JavaDoc makeXMLReader() {
1418        return new com.icl.saxon.aelfred.SAXDriver();
1419    }
1420}
1421
Popular Tags