Show TOC

 XSL TransformationsLocate this document in the navigation structure

Use

You can use the XSL Transformation part of JAXP to transform source documents into result documents, by applying a stylesheet or just converting from one type of source (for example DOM) to a different kind of result (for example SAX). The source and result will represent one and the same document. You can also indent the source document to set a transformer using:

transformer.setOutputProperty(OutputKeys.INDENT, "yes");

transformer.transform(new StreamSoruce("original"), new StreamResult("indented");

Features

The classes related to the XSL Transformations are:

  • Source Types
    • javax.xml.transform.Source
    • javax.xml.transform.stream.StreamSource
    • javax.xml.transform.dom.DOMSource
    • javax.xml.transform.sax.SAXSource
  • Result Types
    • javax.xml.transform.Result
    • javax.xml.transform.StreamResult
    • javax.xml.transform.DOMResult
    • javax.xml.transform.SAXResult
Example
public class JAXPXSLTExample {
  public static void main(String args[]) {
    //get a new TransformerFactory from the underlying
    //implementation
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = null;
    Templates template = null;
    StreamSource xmlSource = null;
    StreamSource xslSource = null;
    StreamResult result = null;
    try {
      // a new StreamSource from a file name
      xmlSource = new StreamSource("data/cars.xml");
      xslSource = new StreamSource("data/cars1.xsl");
      // a new StreamResult to a file name (it is automatically
      //closed on exit)
      result    = new StreamResult("data/cars1.html");
      // get a new Templates object for this stylesheet
      template = factory.newTemplates(xslSource);
      // get a new Transformer from the Templates
      transformer = template.newTransformer();
      // perform the transformation
      transformer.transform(xmlSource, result);
      // it is not needed to close the Stream result since it is
      //output to a file name
    }
  }
}