Sobes.tech
Junior

What is XSLT?

sobes.tech AI

Answer from AI

XSLT (eXtensible Stylesheet Language Transformations) is a language for transforming XML documents. It is used to convert XML into other formats, such as HTML, another XML, or plain text, by applying rules described in an XSLT stylesheet.

Main concepts:

  • XSLT stylesheet: An XML document containing transformation rules.
  • Templates: The main blocks of rules. They match elements or attributes of the source XML and define how to transform them.
  • XPath: A query language for selecting nodes in an XML document. Used in XSLT to determine which parts of XML to apply rules to.
  • XSLT processor: A program that performs the transformation by reading the source XML and the stylesheet, and generating the result.

Java has built-in support for XSLT through JAXP (Java API for XML Processing).

Example of simple XSLT transformation from XML to HTML:

Source XML:

<books>
  <book id="1">
    <title>The Master and Margarita</title>
    <author>Bulgakov M.</author>
  </book>
  <book id="2">
    <title>War and Peace</title>
    <author>Tolstoy L.</author>
  </book>
</books>

XSLT stylesheet (e.g., book.xsl):

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1991/XSL/Transform">
  <xsl:template match="/books">
    <html>
      <head>
        <title>Book List</title>
      </head>
      <body>
        <h1>Book List</h1>
        <ul>
          <xsl:apply-templates select="book"/>
        </ul>
      </body>
    </html>
  </xsl:template>

  <xsl:template match="book">
    <li>
      <b><xsl:value-of select="title"/></b>, Author: <xsl:value-of select="author"/>
    </li>
  </xsl:template>
</xsl:stylesheet>

Java code example for transformation using JAXP:

import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import java.io.*;

public class XSLTExample {

    public static void main(String[] args) {
        try {
            // Create TransformerFactory
            TransformerFactory factory = TransformerFactory.newInstance();

            // Load XSLT stylesheet
            Source xslt = new StreamSource(new File("book.xsl"));
            Transformer transformer = factory.newTransformer(xslt);

            // Load source XML
            Source xml = new StreamSource(new File("books.xml"));

            // Define output
            Result result = new StreamResult(new File("output.html"));

            // Perform transformation
            transformer.transform(xml, result);

            System.out.println("Transformation completed. Result saved in output.html");
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }
}

XSLT is widely used in web development (generating HTML from XML for display), data integration, and XML message processing.

What is XSLT? — Java - sobes.tech