The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > javax.xml.transform  [5 examples] > XSL  [2 examples]

e522. Transforming an XML File with XSL into a DOM Document

    // This method applies the xslFilename to inFilename and
    // returns DOM document containing the result.
    public static Document parseXmlFile(String inFilename, String xslFilename) {
        try {
            // Create transformer factory
            TransformerFactory factory = TransformerFactory.newInstance();
    
            // Use the factory to create a template containing the xsl file
            Templates template = factory.newTemplates(new StreamSource(
                new FileInputStream(xslFilename)));
    
            // Use the template to create a transformer
            Transformer xformer = template.newTransformer();
    
            // Prepare the input file
            Source source = new StreamSource(new FileInputStream(inFilename));
    
            // Create a new document to hold the results
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc = builder.newDocument();
            Result result = new DOMResult(doc);
    
            // Apply the xsl file to the source file and create the DOM tree
            xformer.transform(source, result);
            return doc;
        } catch (ParserConfigurationException e) {
            // An error occurred while creating an empty DOM document
        } catch (FileNotFoundException e) {
        } catch (TransformerConfigurationException e) {
            // An error occurred in the XSL file
        } catch (TransformerException e) {
            // An error occurred while applying the XSL file
        }
        return null;
    }

 Related Examples
e521. The Quintessential Program That Transforms an XML File with XSL


© 2002 Addison-Wesley.