Sobes.tech
Junior

What is XSLT?

sobes.tech AI

Answer from AI

XSLT (eXtensible Stylesheet Language Transformations) is a language used for transforming XML documents into other XML documents, HTML documents, or other formats such as plain text. It is based on the use of templates, which are applied to nodes of the source XML document.

Main concepts of XSLT:

  • Stylesheet Table: An XML document containing transformation rules.
  • Template: A rule defining how to process nodes of the source XML document. Uses xsl:template and xsl:apply-templates elements.
  • XPath: A language for selecting nodes in an XML document. Widely used in XSLT to define conditions and select elements.
  • XSLT Processor: A program that performs the transformation by applying the style sheet to the XML document.

Example of a simple XSLT style sheet:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">
    <html>
      <body>
        <h2>Book List</h2>
        <ul>
          <xsl:for-each select="catalog/book">
            <li>
              <xsl:value-of select="title"/>
            </li>
          </xsl:for-each>
        </ul>
      </body>
    </html>
  </xsl:template>
</xsl:stylesheet>

This example transforms an XML document with book information (<catalog>, <book>, <title>) into an HTML list.

Advantages of XSLT:

  • Standardized language.
  • Declarative approach to transformation.
  • Ability to transform into various formats.
  • Separation of content (XML) from presentation (XSLT).

Disadvantages:

  • Can be complex to understand and debug large style sheets.
  • Performance may be an issue for very large XML documents.

In Java, XSLT transformations are performed using the JAXP API (javax.xml.transform package).

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

public class XSLTExample {
    public static void main(String[] args) {
        try {
            Source xmlInput = new StreamSource("input.xml");
            Source xslInput = new StreamSource("transform.xsl");
            Result xmlOutput = new StreamResult("output.html");
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer(xslInput);
            transformer.transform(xmlInput, xmlOutput);
            System.out.println("Transformation completed.");
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }
}