KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > Examples


1 /*
2  * Copyright 1999-2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 /*
17  * $Id: Examples.java,v 1.16 2004/02/17 19:13:22 minchau Exp $
18  */

19 import java.io.BufferedInputStream JavaDoc;
20 import java.io.BufferedReader JavaDoc;
21 import java.io.File JavaDoc;
22 import java.io.FileInputStream JavaDoc;
23 import java.io.FileNotFoundException JavaDoc;
24 import java.io.IOException JavaDoc;
25 import java.io.InputStream JavaDoc;
26 import java.io.InputStreamReader JavaDoc;
27 import java.io.OutputStreamWriter JavaDoc;
28 import java.io.Reader JavaDoc;
29 import java.io.UnsupportedEncodingException JavaDoc;
30 import java.util.Properties JavaDoc;
31
32 import javax.xml.parsers.DocumentBuilder JavaDoc;
33 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
34 import javax.xml.parsers.ParserConfigurationException JavaDoc;
35 import javax.xml.transform.OutputKeys JavaDoc;
36 import javax.xml.transform.Result JavaDoc;
37 import javax.xml.transform.Source JavaDoc;
38 import javax.xml.transform.Templates JavaDoc;
39 import javax.xml.transform.Transformer JavaDoc;
40 import javax.xml.transform.TransformerConfigurationException JavaDoc;
41 import javax.xml.transform.TransformerException JavaDoc;
42 import javax.xml.transform.TransformerFactory JavaDoc;
43 import javax.xml.transform.dom.DOMResult JavaDoc;
44 import javax.xml.transform.dom.DOMSource JavaDoc;
45 import javax.xml.transform.sax.SAXResult JavaDoc;
46 import javax.xml.transform.sax.SAXSource JavaDoc;
47 import javax.xml.transform.sax.SAXTransformerFactory JavaDoc;
48 import javax.xml.transform.sax.TransformerHandler JavaDoc;
49 import javax.xml.transform.stream.StreamResult JavaDoc;
50 import javax.xml.transform.stream.StreamSource JavaDoc;
51
52 import org.w3c.dom.Node JavaDoc;
53 import org.xml.sax.InputSource JavaDoc;
54 import org.xml.sax.SAXException JavaDoc;
55 import org.xml.sax.XMLFilter JavaDoc;
56 import org.xml.sax.XMLReader JavaDoc;
57 import org.xml.sax.helpers.XMLReaderFactory JavaDoc;
58 /**
59  * Some examples to show how the Simple API for Transformations
60  * could be used.
61  *
62  * Xalan Developers: please see
63  * xml-xalan/test/java/src/org/apache/qetest/trax/ExamplesTest.java
64  * when updating this file, and update that test file as well.
65  *
66  * @author <a HREF="mailto:scott_boag@lotus.com">Scott Boag</a>
67  */

68 public class Examples
69 {
70   /**
71    * Method main
72    */

73   public static void main(String JavaDoc argv[])
74           throws TransformerException JavaDoc, TransformerConfigurationException JavaDoc, IOException JavaDoc, SAXException JavaDoc,
75                  ParserConfigurationException JavaDoc, FileNotFoundException JavaDoc
76   {
77     System.out.println("\n\n==== exampleSimple ====");
78     try {
79         exampleSimple1("xml/foo.xml", "xsl/foo.xsl");
80     } catch( Exception JavaDoc ex ) {
81         handleException(ex);
82     }
83     
84     System.out.println("\n\n==== exampleSimple2 (see foo.out) ====");
85     try {
86         exampleSimple2("xml/foo.xml", "xsl/foo.xsl");
87     } catch( Exception JavaDoc ex ) {
88         handleException(ex);
89     }
90     
91     System.out.println("\n\n==== exampleFromStream ====");
92     try {
93         exampleFromStream("xml/foo.xml", "xsl/foo.xsl");
94     } catch( Exception JavaDoc ex ) {
95         handleException(ex);
96     }
97     
98     System.out.println("\n\n==== exampleFromReader ====");
99     try {
100         exampleFromReader("xml/foo.xml", "xsl/foo.xsl");
101     } catch( Exception JavaDoc ex ) {
102         handleException(ex);
103     }
104     
105     System.out.println("\n\n==== exampleUseTemplatesObj ====");
106     try {
107         exampleUseTemplatesObj("xml/foo.xml", "xml/baz.xml", "xsl/foo.xsl");
108     } catch( Exception JavaDoc ex ) {
109         handleException(ex);
110     }
111     
112     System.out.println("\n\n==== exampleContentHandlerToContentHandler ====");
113     try {
114         exampleContentHandlerToContentHandler("xml/foo.xml", "xsl/foo.xsl");
115     } catch( Exception JavaDoc ex ) {
116         handleException(ex);
117     }
118     
119     System.out.println("\n\n==== exampleXMLReader ====");
120     try {
121         exampleXMLReader("xml/foo.xml", "xsl/foo.xsl");
122     } catch( Exception JavaDoc ex ) {
123         handleException(ex);
124     }
125     
126     System.out.println("\n\n==== exampleXMLFilter ====");
127     try {
128         exampleXMLFilter("xml/foo.xml", "xsl/foo.xsl");
129     } catch( Exception JavaDoc ex ) {
130         handleException(ex);
131     }
132     
133     System.out.println("\n\n==== exampleXMLFilterChain ====");
134     try {
135         exampleXMLFilterChain("xml/foo.xml", "xsl/foo.xsl", "xsl/foo2.xsl", "xsl/foo3.xsl");
136     } catch( Exception JavaDoc ex ) {
137         handleException(ex);
138     }
139     
140     System.out.println("\n\n==== exampleDOM2DOM ====");
141     try {
142         exampleDOM2DOM("xml/foo.xml", "xsl/foo.xsl");
143     } catch( Exception JavaDoc ex ) {
144         handleException(ex);
145     }
146     
147     System.out.println("\n\n==== exampleParam ====");
148     try {
149         exampleParam("xml/foo.xml", "xsl/foo.xsl");
150     } catch( Exception JavaDoc ex ) {
151         handleException(ex);
152     }
153     
154     System.out.println("\n\n==== exampleTransformerReuse ====");
155     try {
156         exampleTransformerReuse("xml/foo.xml", "xsl/foo.xsl");
157     } catch( Exception JavaDoc ex ) {
158         handleException(ex);
159     }
160     
161     System.out.println("\n\n==== exampleOutputProperties ====");
162     try {
163         exampleOutputProperties("xml/foo.xml", "xsl/foo.xsl");
164     } catch( Exception JavaDoc ex ) {
165         handleException(ex);
166     }
167     
168     System.out.println("\n\n==== exampleUseAssociated ====");
169     try {
170         exampleUseAssociated("xml/foo.xml");
171     } catch( Exception JavaDoc ex ) {
172         handleException(ex);
173     }
174     
175     System.out.println("\n\n==== exampleContentHandler2DOM ====");
176     try {
177         exampleContentHandler2DOM("xml/foo.xml", "xsl/foo.xsl");
178     } catch( Exception JavaDoc ex ) {
179         handleException(ex);
180     }
181     
182     System.out.println("\n\n==== exampleAsSerializer ====");
183     try {
184         exampleAsSerializer("xml/foo.xml", "xsl/foo.xsl");
185     } catch( Exception JavaDoc ex ) {
186         handleException(ex);
187     }
188     
189     System.out.println("\n\n==== exampleContentHandler2DOM ====");
190     try {
191         exampleContentHandler2DOM("xml/foo.xml", "xsl/foo.xsl");
192     } catch( Exception JavaDoc ex ) {
193         handleException(ex);
194     }
195
196     System.out.println("\n==== done! ====");
197   }
198   
199   /**
200    * Show the simplest possible transformation from system id
201    * to output stream.
202    */

203   public static void exampleSimple1(String JavaDoc sourceID, String JavaDoc xslID)
204     throws TransformerException JavaDoc, TransformerConfigurationException JavaDoc
205   {
206     // Create a transform factory instance.
207
TransformerFactory JavaDoc tfactory = TransformerFactory.newInstance();
208     
209     // Create a transformer for the stylesheet.
210
Transformer JavaDoc transformer
211       = tfactory.newTransformer(new StreamSource JavaDoc(xslID));
212     
213     // Transform the source XML to System.out.
214
transformer.transform( new StreamSource JavaDoc(sourceID),
215                            new StreamResult JavaDoc(new OutputStreamWriter JavaDoc(System.out)));
216   }
217   
218   /**
219    * Show the simplest possible transformation from File
220    * to a File.
221    */

222   public static void exampleSimple2(String JavaDoc sourceID, String JavaDoc xslID)
223     throws TransformerException JavaDoc, TransformerConfigurationException JavaDoc
224   {
225     // Create a transform factory instance.
226
TransformerFactory JavaDoc tfactory = TransformerFactory.newInstance();
227     
228     // Create a transformer for the stylesheet.
229
Transformer JavaDoc transformer
230       = tfactory.newTransformer(new StreamSource JavaDoc(xslID));
231     
232     // Transform the source XML to foo.out.
233
transformer.transform( new StreamSource JavaDoc(new File JavaDoc(sourceID)),
234                            new StreamResult JavaDoc(new File JavaDoc("foo.out")));
235   }
236
237   
238   /**
239    * Show simple transformation from input stream to output stream.
240    */

241   public static void exampleFromStream(String JavaDoc sourceID, String JavaDoc xslID)
242     throws TransformerException JavaDoc, TransformerConfigurationException JavaDoc,
243            FileNotFoundException JavaDoc
244   {
245     // Create a transform factory instance.
246
TransformerFactory JavaDoc tfactory = TransformerFactory.newInstance();
247
248     InputStream JavaDoc xslIS = new BufferedInputStream JavaDoc(new FileInputStream JavaDoc(xslID));
249     StreamSource JavaDoc xslSource = new StreamSource JavaDoc(xslIS);
250     // Note that if we don't do this, relative URLs can not be resolved correctly!
251
xslSource.setSystemId(xslID);
252
253     // Create a transformer for the stylesheet.
254
Transformer JavaDoc transformer = tfactory.newTransformer(xslSource);
255     
256     InputStream JavaDoc xmlIS = new BufferedInputStream JavaDoc(new FileInputStream JavaDoc(sourceID));
257     StreamSource JavaDoc xmlSource = new StreamSource JavaDoc(xmlIS);
258     // Note that if we don't do this, relative URLs can not be resolved correctly!
259
xmlSource.setSystemId(sourceID);
260     
261     // Transform the source XML to System.out.
262
transformer.transform( xmlSource, new StreamResult JavaDoc(new OutputStreamWriter JavaDoc(System.out)));
263   }
264   
265   /**
266    * Show simple transformation from reader to output stream. In general
267    * this use case is discouraged, since the XML encoding can not be
268    * processed.
269    */

270   public static void exampleFromReader(String JavaDoc sourceID, String JavaDoc xslID)
271     throws TransformerException JavaDoc, TransformerConfigurationException JavaDoc,
272            FileNotFoundException JavaDoc, UnsupportedEncodingException JavaDoc
273   {
274     // Create a transform factory instance.
275
TransformerFactory JavaDoc tfactory = TransformerFactory.newInstance();
276
277     // Note that in this case the XML encoding can not be processed!
278
Reader JavaDoc xslReader = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(new FileInputStream JavaDoc(xslID), "UTF-8"));
279     StreamSource JavaDoc xslSource = new StreamSource JavaDoc(xslReader);
280     // Note that if we don't do this, relative URLs can not be resolved correctly!
281
xslSource.setSystemId(xslID);
282
283     // Create a transformer for the stylesheet.
284
Transformer JavaDoc transformer = tfactory.newTransformer(xslSource);
285     
286     // Note that in this case the XML encoding can not be processed!
287
Reader JavaDoc xmlReader = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(new FileInputStream JavaDoc(sourceID), "UTF-8"));
288     StreamSource JavaDoc xmlSource = new StreamSource JavaDoc(xmlReader);
289     // Note that if we don't do this, relative URLs can not be resolved correctly!
290
xmlSource.setSystemId(sourceID);
291     
292     // Transform the source XML to System.out.
293
transformer.transform( xmlSource, new StreamResult JavaDoc(new OutputStreamWriter JavaDoc(System.out)));
294   }
295
296
297  
298   /**
299    * Show the simplest possible transformation from system id to output stream.
300    */

301   public static void exampleUseTemplatesObj(String JavaDoc sourceID1,
302                                     String JavaDoc sourceID2,
303                                     String JavaDoc xslID)
304           throws TransformerException JavaDoc, TransformerConfigurationException JavaDoc
305   {
306
307     TransformerFactory JavaDoc tfactory = TransformerFactory.newInstance();
308     
309     // Create a templates object, which is the processed,
310
// thread-safe representation of the stylesheet.
311
Templates JavaDoc templates = tfactory.newTemplates(new StreamSource JavaDoc(xslID));
312
313     // Illustrate the fact that you can make multiple transformers
314
// from the same template.
315
Transformer JavaDoc transformer1 = templates.newTransformer();
316     Transformer JavaDoc transformer2 = templates.newTransformer();
317     
318     System.out.println("\n\n----- transform of "+sourceID1+" -----");
319     
320     transformer1.transform(new StreamSource JavaDoc(sourceID1),
321                           new StreamResult JavaDoc(new OutputStreamWriter JavaDoc(System.out)));
322     
323     System.out.println("\n\n----- transform of "+sourceID2+" -----");
324     
325     transformer2.transform(new StreamSource JavaDoc(sourceID2),
326                           new StreamResult JavaDoc(new OutputStreamWriter JavaDoc(System.out)));
327   }
328   
329
330
331   /**
332    * Show the Transformer using SAX events in and SAX events out.
333    */

334   public static void exampleContentHandlerToContentHandler(String JavaDoc sourceID,
335                                                            String JavaDoc xslID)
336           throws TransformerException JavaDoc,
337                  TransformerConfigurationException JavaDoc,
338                  SAXException JavaDoc, IOException JavaDoc
339   {
340     TransformerFactory JavaDoc tfactory = TransformerFactory.newInstance();
341
342     // Does this factory support SAX features?
343
if (tfactory.getFeature(SAXSource.FEATURE))
344     {
345       // If so, we can safely cast.
346
SAXTransformerFactory JavaDoc stfactory = ((SAXTransformerFactory JavaDoc) tfactory);
347       
348       // A TransformerHandler is a ContentHandler that will listen for
349
// SAX events, and transform them to the result.
350
TransformerHandler JavaDoc handler
351         = stfactory.newTransformerHandler(new StreamSource JavaDoc(xslID));
352
353       // Set the result handling to be a serialization to System.out.
354
Result JavaDoc result = new SAXResult JavaDoc(new ExampleContentHandler());
355       handler.setResult(result);
356       
357       // Create a reader, and set it's content handler to be the TransformerHandler.
358
XMLReader JavaDoc reader=null;
359
360       // Use JAXP1.1 ( if possible )
361
try {
362       javax.xml.parsers.SAXParserFactory JavaDoc factory=
363           javax.xml.parsers.SAXParserFactory.newInstance();
364       factory.setNamespaceAware( true );
365       javax.xml.parsers.SAXParser JavaDoc jaxpParser=
366           factory.newSAXParser();
367       reader=jaxpParser.getXMLReader();
368       
369       } catch( javax.xml.parsers.ParserConfigurationException JavaDoc ex ) {
370       throw new org.xml.sax.SAXException JavaDoc( ex );
371       } catch( javax.xml.parsers.FactoryConfigurationError JavaDoc ex1 ) {
372       throw new org.xml.sax.SAXException JavaDoc( ex1.toString() );
373       } catch( NoSuchMethodError JavaDoc ex2 ) {
374       }
375       if( reader==null ) reader = XMLReaderFactory.createXMLReader();
376       reader.setContentHandler(handler);
377       
378       // It's a good idea for the parser to send lexical events.
379
// The TransformerHandler is also a LexicalHandler.
380
reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler);
381       
382       // Parse the source XML, and send the parse events to the TransformerHandler.
383
reader.parse(sourceID);
384     }
385     else
386     {
387       System.out.println(
388         "Can't do exampleContentHandlerToContentHandler because tfactory is not a SAXTransformerFactory");
389     }
390   }
391   
392   /**
393    * Show the Transformer as a SAX2 XMLReader. An XMLFilter obtained
394    * from newXMLFilter should act as a transforming XMLReader if setParent is not
395    * called. Internally, an XMLReader is created as the parent for the XMLFilter.
396    */

397   public static void exampleXMLReader(String JavaDoc sourceID, String JavaDoc xslID)
398           throws TransformerException JavaDoc, TransformerConfigurationException JavaDoc, SAXException JavaDoc, IOException JavaDoc // , ParserConfigurationException
399
{
400     TransformerFactory JavaDoc tfactory = TransformerFactory.newInstance();
401     if(tfactory.getFeature(SAXSource.FEATURE))
402     {
403       XMLReader JavaDoc reader
404         = ((SAXTransformerFactory JavaDoc) tfactory).newXMLFilter(new StreamSource JavaDoc(xslID));
405       
406       reader.setContentHandler(new ExampleContentHandler());
407
408       reader.parse(new InputSource JavaDoc(sourceID));
409     }
410     else
411       System.out.println("tfactory does not support SAX features!");
412   }
413
414   /**
415    * Show the Transformer as a simple XMLFilter. This is pretty similar
416    * to exampleXMLReader, except that here the parent XMLReader is created
417    * by the caller, instead of automatically within the XMLFilter. This
418    * gives the caller more direct control over the parent reader.
419    */

420   public static void exampleXMLFilter(String JavaDoc sourceID, String JavaDoc xslID)
421           throws TransformerException JavaDoc, TransformerConfigurationException JavaDoc, SAXException JavaDoc, IOException JavaDoc // , ParserConfigurationException
422
{
423     TransformerFactory JavaDoc tfactory = TransformerFactory.newInstance();
424
425     XMLReader JavaDoc reader=null;
426     
427     // Use JAXP1.1 ( if possible )
428
try {
429     javax.xml.parsers.SAXParserFactory JavaDoc factory=
430         javax.xml.parsers.SAXParserFactory.newInstance();
431       factory.setNamespaceAware( true );
432       javax.xml.parsers.SAXParser JavaDoc jaxpParser=
433         factory.newSAXParser();
434     reader=jaxpParser.getXMLReader();
435     
436     } catch( javax.xml.parsers.ParserConfigurationException JavaDoc ex ) {
437     throw new org.xml.sax.SAXException JavaDoc( ex );
438     } catch( javax.xml.parsers.FactoryConfigurationError JavaDoc ex1 ) {
439     throw new org.xml.sax.SAXException JavaDoc( ex1.toString() );
440     } catch( NoSuchMethodError JavaDoc ex2 ) {
441     }
442     if( reader==null ) reader = XMLReaderFactory.createXMLReader();
443     // The transformer will use a SAX parser as it's reader.
444
reader.setContentHandler(new ExampleContentHandler());
445     try
446     {
447       reader.setFeature("http://xml.org/sax/features/namespace-prefixes",
448                         true);
449       reader.setFeature("http://apache.org/xml/features/validation/dynamic",
450                         true);
451     }
452     catch (SAXException JavaDoc se)
453     {
454
455       // What can we do?
456
// TODO: User diagnostics.
457
}
458
459     XMLFilter JavaDoc filter
460       = ((SAXTransformerFactory JavaDoc) tfactory).newXMLFilter(new StreamSource JavaDoc(xslID));
461
462     filter.setParent(reader);
463
464     // Now, when you call transformer.parse, it will set itself as
465
// the content handler for the parser object (it's "parent"), and
466
// will then call the parse method on the parser.
467
filter.parse(new InputSource JavaDoc(sourceID));
468   }
469
470   /**
471    * This example shows how to chain events from one Transformer
472    * to another transformer, using the Transformer as a
473    * SAX2 XMLFilter/XMLReader.
474    */

475   public static void exampleXMLFilterChain(
476                                            String JavaDoc sourceID, String JavaDoc xslID_1,
477                                            String JavaDoc xslID_2, String JavaDoc xslID_3)
478     throws TransformerException JavaDoc, TransformerConfigurationException JavaDoc, SAXException JavaDoc, IOException JavaDoc
479   {
480     TransformerFactory JavaDoc tfactory = TransformerFactory.newInstance();
481     
482     Templates JavaDoc stylesheet1 = tfactory.newTemplates(new StreamSource JavaDoc(xslID_1));
483     Transformer JavaDoc transformer1 = stylesheet1.newTransformer();
484     
485      // If one success, assume all will succeed.
486
if (tfactory.getFeature(SAXSource.FEATURE))
487     {
488       SAXTransformerFactory JavaDoc stf = (SAXTransformerFactory JavaDoc)tfactory;
489       XMLReader JavaDoc reader=null;
490
491       // Use JAXP1.1 ( if possible )
492
try {
493       javax.xml.parsers.SAXParserFactory JavaDoc factory=
494           javax.xml.parsers.SAXParserFactory.newInstance();
495       factory.setNamespaceAware( true );
496       javax.xml.parsers.SAXParser JavaDoc jaxpParser=
497           factory.newSAXParser();
498       reader=jaxpParser.getXMLReader();
499       
500       } catch( javax.xml.parsers.ParserConfigurationException JavaDoc ex ) {
501       throw new org.xml.sax.SAXException JavaDoc( ex );
502       } catch( javax.xml.parsers.FactoryConfigurationError JavaDoc ex1 ) {
503       throw new org.xml.sax.SAXException JavaDoc( ex1.toString() );
504       } catch( NoSuchMethodError JavaDoc ex2 ) {
505       }
506       if( reader==null ) reader = XMLReaderFactory.createXMLReader();
507
508       XMLFilter JavaDoc filter1 = stf.newXMLFilter(new StreamSource JavaDoc(xslID_1));
509       XMLFilter JavaDoc filter2 = stf.newXMLFilter(new StreamSource JavaDoc(xslID_2));
510       XMLFilter JavaDoc filter3 = stf.newXMLFilter(new StreamSource JavaDoc(xslID_3));
511
512       if (null != filter1) // If one success, assume all were success.
513
{
514         // transformer1 will use a SAX parser as it's reader.
515
filter1.setParent(reader);
516
517         // transformer2 will use transformer1 as it's reader.
518
filter2.setParent(filter1);
519
520         // transform3 will use transform2 as it's reader.
521
filter3.setParent(filter2);
522
523         filter3.setContentHandler(new ExampleContentHandler());
524         // filter3.setContentHandler(new org.xml.sax.helpers.DefaultHandler());
525

526         // Now, when you call transformer3 to parse, it will set
527
// itself as the ContentHandler for transform2, and
528
// call transform2.parse, which will set itself as the
529
// content handler for transform1, and call transform1.parse,
530
// which will set itself as the content listener for the
531
// SAX parser, and call parser.parse(new InputSource("xml/foo.xml")).
532
filter3.parse(new InputSource JavaDoc(sourceID));
533       }
534       else
535       {
536         System.out.println(
537                            "Can't do exampleXMLFilter because "+
538                            "tfactory doesn't support asXMLFilter()");
539       }
540     }
541     else
542     {
543       System.out.println(
544                          "Can't do exampleXMLFilter because "+
545                          "tfactory is not a SAXTransformerFactory");
546     }
547   }
548
549   /**
550    * Show how to transform a DOM tree into another DOM tree.
551    * This uses the javax.xml.parsers to parse an XML file into a
552    * DOM, and create an output DOM.
553    */

554   public static Node JavaDoc exampleDOM2DOM(String JavaDoc sourceID, String JavaDoc xslID)
555     throws TransformerException JavaDoc, TransformerConfigurationException JavaDoc, SAXException JavaDoc, IOException JavaDoc,
556     ParserConfigurationException JavaDoc
557   {
558     TransformerFactory JavaDoc tfactory = TransformerFactory.newInstance();
559
560     if (tfactory.getFeature(DOMSource.FEATURE))
561     {
562       Templates JavaDoc templates;
563
564       {
565         DocumentBuilderFactory JavaDoc dfactory =
566           DocumentBuilderFactory.newInstance();
567         dfactory.setNamespaceAware(true);
568         DocumentBuilder JavaDoc docBuilder = dfactory.newDocumentBuilder();
569         org.w3c.dom.Document JavaDoc outNode = docBuilder.newDocument();
570         Node JavaDoc doc = docBuilder.parse(new InputSource JavaDoc(xslID));
571  
572         DOMSource JavaDoc dsource = new DOMSource JavaDoc(doc);
573         // If we don't do this, the transformer won't know how to
574
// resolve relative URLs in the stylesheet.
575
dsource.setSystemId(xslID);
576
577         templates = tfactory.newTemplates(dsource);
578       }
579
580       Transformer JavaDoc transformer = templates.newTransformer();
581       DocumentBuilderFactory JavaDoc dfactory = DocumentBuilderFactory.newInstance();
582       // Note you must always setNamespaceAware when building .xsl stylesheets
583
dfactory.setNamespaceAware(true);
584       DocumentBuilder JavaDoc docBuilder = dfactory.newDocumentBuilder();
585       org.w3c.dom.Document JavaDoc outNode = docBuilder.newDocument();
586       Node JavaDoc doc = docBuilder.parse(new InputSource JavaDoc(sourceID));
587
588       transformer.transform(new DOMSource JavaDoc(doc), new DOMResult JavaDoc(outNode));
589       
590       Transformer JavaDoc serializer = tfactory.newTransformer();
591       serializer.transform(new DOMSource JavaDoc(outNode), new StreamResult JavaDoc(new OutputStreamWriter JavaDoc(System.out)));
592
593       return outNode;
594     }
595     else
596     {
597       throw new org.xml.sax
598
JavaDoc        .SAXNotSupportedException("DOM node processing not supported!");
599     }
600   }
601
602   /**
603    * This shows how to set a parameter for use by the templates. Use
604    * two transformers to show that different parameters may be set
605    * on different transformers.
606    */

607   public static void exampleParam(String JavaDoc sourceID,
608                                   String JavaDoc xslID)
609     throws TransformerException JavaDoc, TransformerConfigurationException JavaDoc
610   {
611     TransformerFactory JavaDoc tfactory = TransformerFactory.newInstance();
612     Templates JavaDoc templates = tfactory.newTemplates(new StreamSource JavaDoc(xslID));
613     Transformer JavaDoc transformer1 = templates.newTransformer();
614     Transformer JavaDoc transformer2 = templates.newTransformer();
615
616     transformer1.setParameter("a-param",
617                               "hello to you!");
618     transformer1.transform(new StreamSource JavaDoc(sourceID),
619                            new StreamResult JavaDoc(new OutputStreamWriter JavaDoc(System.out)));
620     
621     System.out.println("\n=========");
622     
623     transformer2.setOutputProperty(OutputKeys.INDENT, "yes");
624     transformer2.transform(new StreamSource JavaDoc(sourceID),
625                            new StreamResult JavaDoc(new OutputStreamWriter JavaDoc(System.out)));
626   }
627   
628   /**
629    * Show the that a transformer can be reused, and show resetting
630    * a parameter on the transformer.
631    */

632   public static void exampleTransformerReuse(String JavaDoc sourceID, String JavaDoc xslID)
633     throws TransformerException JavaDoc, TransformerConfigurationException JavaDoc
634   {
635     // Create a transform factory instance.
636
TransformerFactory JavaDoc tfactory = TransformerFactory.newInstance();
637     
638     // Create a transformer for the stylesheet.
639
Transformer JavaDoc transformer
640       = tfactory.newTransformer(new StreamSource JavaDoc(xslID));
641     
642     transformer.setParameter("a-param",
643                               "hello to you!");
644     
645     // Transform the source XML to System.out.
646
transformer.transform( new StreamSource JavaDoc(sourceID),
647                            new StreamResult JavaDoc(new OutputStreamWriter JavaDoc(System.out)));
648
649     System.out.println("\n=========\n");
650
651     transformer.setParameter("a-param",
652                               "hello to me!");
653     transformer.setOutputProperty(OutputKeys.INDENT, "yes");
654
655     // Transform the source XML to System.out.
656
transformer.transform( new StreamSource JavaDoc(sourceID),
657                            new StreamResult JavaDoc(new OutputStreamWriter JavaDoc(System.out)));
658   }
659
660   /**
661    * Show how to override output properties.
662    */

663   public static void exampleOutputProperties(String JavaDoc sourceID, String JavaDoc xslID)
664     throws TransformerException JavaDoc, TransformerConfigurationException JavaDoc
665   {
666
667     TransformerFactory JavaDoc tfactory = TransformerFactory.newInstance();
668     Templates JavaDoc templates = tfactory.newTemplates(new StreamSource JavaDoc(xslID));
669     Properties JavaDoc oprops = templates.getOutputProperties();
670
671     oprops.put(OutputKeys.INDENT, "yes");
672
673     Transformer JavaDoc transformer = templates.newTransformer();
674
675     transformer.setOutputProperties(oprops);
676     transformer.transform(new StreamSource JavaDoc(sourceID),
677                           new StreamResult JavaDoc(new OutputStreamWriter JavaDoc(System.out)));
678   }
679
680   /**
681    * Show how to get stylesheets that are associated with a given
682    * xml document via the xml-stylesheet PI (see http://www.w3.org/TR/xml-stylesheet/).
683    */

684   public static void exampleUseAssociated(String JavaDoc sourceID)
685     throws TransformerException JavaDoc, TransformerConfigurationException JavaDoc
686   {
687     TransformerFactory JavaDoc tfactory = TransformerFactory.newInstance();
688
689     // The DOM tfactory will have it's own way, based on DOM2,
690
// of getting associated stylesheets.
691
if (tfactory instanceof SAXTransformerFactory JavaDoc)
692     {
693       SAXTransformerFactory JavaDoc stf = ((SAXTransformerFactory JavaDoc) tfactory);
694       Source JavaDoc sources =
695         stf.getAssociatedStylesheet(new StreamSource JavaDoc(sourceID),
696           null, null, null);
697
698       if(null != sources)
699       {
700         Transformer JavaDoc transformer = tfactory.newTransformer(sources);
701
702         transformer.transform(new StreamSource JavaDoc(sourceID),
703                               new StreamResult JavaDoc(new OutputStreamWriter JavaDoc(System.out)));
704       }
705       else
706       {
707         System.out.println("Can't find the associated stylesheet!");
708       }
709     }
710   }
711   
712   /**
713    * Show the Transformer using SAX events in and DOM nodes out.
714    */

715   public static void exampleContentHandler2DOM(String JavaDoc sourceID, String JavaDoc xslID)
716           throws TransformerException JavaDoc, TransformerConfigurationException JavaDoc, SAXException JavaDoc, IOException JavaDoc, ParserConfigurationException JavaDoc
717   {
718     TransformerFactory JavaDoc tfactory = TransformerFactory.newInstance();
719
720     // Make sure the transformer factory we obtained supports both
721
// DOM and SAX.
722
if (tfactory.getFeature(SAXSource.FEATURE)
723         && tfactory.getFeature(DOMSource.FEATURE))
724     {
725       // We can now safely cast to a SAXTransformerFactory.
726
SAXTransformerFactory JavaDoc sfactory = (SAXTransformerFactory JavaDoc) tfactory;
727       
728       // Create an Document node as the root for the output.
729
DocumentBuilderFactory JavaDoc dfactory
730         = DocumentBuilderFactory.newInstance();
731       DocumentBuilder JavaDoc docBuilder = dfactory.newDocumentBuilder();
732       org.w3c.dom.Document JavaDoc outNode = docBuilder.newDocument();
733       
734       // Create a ContentHandler that can liston to SAX events
735
// and transform the output to DOM nodes.
736
TransformerHandler JavaDoc handler
737         = sfactory.newTransformerHandler(new StreamSource JavaDoc(xslID));
738       handler.setResult(new DOMResult JavaDoc(outNode));
739       
740       // Create a reader and set it's ContentHandler to be the
741
// transformer.
742
XMLReader JavaDoc reader=null;
743
744       // Use JAXP1.1 ( if possible )
745
try {
746       javax.xml.parsers.SAXParserFactory JavaDoc factory=
747           javax.xml.parsers.SAXParserFactory.newInstance();
748       factory.setNamespaceAware( true );
749       javax.xml.parsers.SAXParser JavaDoc jaxpParser=
750           factory.newSAXParser();
751       reader=jaxpParser.getXMLReader();
752       
753       } catch( javax.xml.parsers.ParserConfigurationException JavaDoc ex ) {
754       throw new org.xml.sax.SAXException JavaDoc( ex );
755       } catch( javax.xml.parsers.FactoryConfigurationError JavaDoc ex1 ) {
756       throw new org.xml.sax.SAXException JavaDoc( ex1.toString() );
757       } catch( NoSuchMethodError JavaDoc ex2 ) {
758       }
759       if( reader==null ) reader= XMLReaderFactory.createXMLReader();
760       reader.setContentHandler(handler);
761       reader.setProperty("http://xml.org/sax/properties/lexical-handler",
762                          handler);
763       
764       // Send the SAX events from the parser to the transformer,
765
// and thus to the DOM tree.
766
reader.parse(sourceID);
767       
768       // Serialize the node for diagnosis.
769
exampleSerializeNode(outNode);
770     }
771     else
772     {
773       System.out.println(
774         "Can't do exampleContentHandlerToContentHandler because tfactory is not a SAXTransformerFactory");
775     }
776   }
777   
778   /**
779    * Serialize a node to System.out.
780    */

781   public static void exampleSerializeNode(Node JavaDoc node)
782     throws TransformerException JavaDoc, TransformerConfigurationException JavaDoc, SAXException JavaDoc, IOException JavaDoc,
783     ParserConfigurationException JavaDoc
784   {
785     TransformerFactory JavaDoc tfactory = TransformerFactory.newInstance();
786     
787     // This creates a transformer that does a simple identity transform,
788
// and thus can be used for all intents and purposes as a serializer.
789
Transformer JavaDoc serializer = tfactory.newTransformer();
790     
791     serializer.setOutputProperty(OutputKeys.INDENT, "yes");
792     serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
793     serializer.transform(new DOMSource JavaDoc(node),
794                          new StreamResult JavaDoc(new OutputStreamWriter JavaDoc(System.out)));
795   }
796   
797   /**
798    * A fuller example showing how the TrAX interface can be used
799    * to serialize a DOM tree.
800    */

801   public static void exampleAsSerializer(String JavaDoc sourceID, String JavaDoc xslID)
802     throws TransformerException JavaDoc, TransformerConfigurationException JavaDoc, SAXException JavaDoc, IOException JavaDoc,
803     ParserConfigurationException JavaDoc
804   {
805     DocumentBuilderFactory JavaDoc dfactory = DocumentBuilderFactory.newInstance();
806     DocumentBuilder JavaDoc docBuilder = dfactory.newDocumentBuilder();
807     org.w3c.dom.Document JavaDoc outNode = docBuilder.newDocument();
808     Node JavaDoc doc = docBuilder.parse(new InputSource JavaDoc(sourceID));
809
810     TransformerFactory JavaDoc tfactory = TransformerFactory.newInstance();
811     
812     // This creates a transformer that does a simple identity transform,
813
// and thus can be used for all intents and purposes as a serializer.
814
Transformer JavaDoc serializer = tfactory.newTransformer();
815     
816     Properties JavaDoc oprops = new Properties JavaDoc();
817     oprops.put("method", "html");
818     serializer.setOutputProperties(oprops);
819     serializer.transform(new DOMSource JavaDoc(doc),
820                          new StreamResult JavaDoc(new OutputStreamWriter JavaDoc(System.out)));
821   }
822   
823
824   private static void handleException( Exception JavaDoc ex ) {
825     System.out.println("EXCEPTION: " );
826     ex.printStackTrace();
827     
828     if( ex instanceof TransformerConfigurationException JavaDoc ) {
829       System.out.println();
830       System.out.println("Internal exception: " );
831       Throwable JavaDoc ex1=((TransformerConfigurationException JavaDoc)ex).getException();
832       ex1.printStackTrace();
833
834       if( ex1 instanceof SAXException JavaDoc ) {
835       Exception JavaDoc ex2=((SAXException JavaDoc)ex1).getException();
836       System.out.println("Internal sub-exception: " );
837       ex2.printStackTrace();
838       }
839     }
840   }
841
842 }
843
Popular Tags