XML - XSLT

What is XSLT?

XSLT is a language used to transform XML documents into other formats, like:

  • Another XML file

  • HTML (for web pages)

  • Plain text

  • Even PDF (via intermediate formats)

 Think of it like this:

  • XML is your data (like student records).

  • XSLT is your template/stylesheet.

  • You apply the XSLT to the XML to produce a new result, like an HTML table or another structured XML file.

 

 Why use XSLT?

  • To display XML in a browser as HTML.

  • To convert one XML structure into another.

  • To extract only part of the XML data.

  • To reformat data for different systems.

 

Key Concepts of XSLT

1. XML Input

The data you want to transform.

<students>
  <student>
    <name>Alice</name>
    <grade>A</grade>
  </student>
  <student>
    <name>Bob</name>
    <grade>B</grade>
  </student>
</students>

 

2. XSLT Stylesheet

Defines how to transform the XML. It's written in XML too!

<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <!-- Output HTML -->
  <xsl:output method="html"/>

  <!-- Match the root element -->
  <xsl:template match="/students">
    <html>
      <body>
        <h2>Student Grades</h2>
        <ul>
          <xsl:for-each select="student">
            <li>
              <xsl:value-of select="name"/> - 
              <xsl:value-of select="grade"/>
            </li>
          </xsl:for-each>
        </ul>
      </body>
    </html>
  </xsl:template>

</xsl:stylesheet>

XSLT Elements

Element Purpose
<xsl:stylesheet> or <xsl:transform> Root of the XSLT file
<xsl:template match="..."> Matches parts of the XML to transform
<xsl:value-of select="..."/> Extracts the value of a node
<xsl:for-each select="..."> Loops over a set of nodes
<xsl:if> Conditional logic
<xsl:choose> / <xsl:when> / <xsl:otherwise> More complex conditionals
<xsl:apply-templates> Applies other templates (recursive processing)