Processing Flow of XSL
The XSL converter constructs three trees:
- A source tree derived from the XML document.
- A stylesheet tree derived from the XSL stylesheet file.
- A result tree produced from the source tree and the stylesheet tree.
Root Element: xsl:stylesheet
The xsl:stylesheet element is the root component of an XSL template. All other XSLT components must be placed inside it. This is an XSL rule with no exceptions.
An XSL stylesheet file consists of a series of template rules. Each template rule is represented by an xsl:template element. A template rule contains a matching pattern (match/select) that specifies which parts of the source tree the rule applies to.
Built-in template rules: By default, character data from the source file is output as-is. As soon as a custom template rule replaces the built-in rule for the root node, the built-in rule for the root node is no longer activated.
XSL Nodes
Root Node
<xsl:template match="/">
</xsl:template>
Text Node
<xsl:template match="text()">
<xsl:value-of select="."/>
</xsl:template>
Attribute Node
<xsl:template match="@*">
<xsl:value-of select="."/>
</xsl:template>
The xsl:apply-templates Element
xsl:apply-templates can be used in two ways:
- With a
selectattribute to specify which template rules should be executed. - Without a
selectattribute (or any other attribute) to process all child nodes of the current node.
<xsl:template match="Book">
<HTML>
<BODY>
<xsl:apply-templates select="Content"/>
</BODY>
</HTML>
</xsl:template>
The xsl:value-of Element
For xsl:value-of, the select attribute determines which node's content or attribute value to extract.
<xsl:template match="Book">
<HTML>
<HEAD>
<TITLE><xsl:value-of select="Title"/></TITLE>
</HEAD>
</HTML>
</xsl:template>
The position() functon returns the numeric position of the currrent node, starting from 1.
<xsl:template match="Book">
<HTML>
<HEAD>
<TD><xsl:value-of select="position()"/></TD>
</HEAD>
</HTML>
</xsl:template>
The pipe symbol | is the OR operator. In the condition [Novel:Name | Novel:Last], the template rule applies if the Novel:Name element has either a Novel:First or a Novel:Last child element.
<xsl:template match="Novel:Name[Novel:First | Novel:Last]">
<xsl:apply-templates select="Novel:First"/>
<xsl:apply-templates select="Novel:Last"/>
</xsl:template>
<xsl:template match="Novel:Name">
<xsl:apply-templates />
</xsl:template>
The xsl:choose Element
This element works like an if-else if statement in programming languages.
<xsl:template match="balance">
<xsl:choose>
<xsl:when test="not(text())">
-
</xsl:when>
<xsl:when test="text()">
<xsl:value-of select="."/>
</xsl:when>
</xsl:choose>
</xsl:template>
In addition to xsl:when, xsl:choose has an xsl:otherwise element that acts as the final else branch.
The xsl:if Element
xsl:if is used for single test conditions. XSLT does not provide xsl:else or xsl:elif elements.
<xsl:template match="balance">
<xsl:if test="not(position()=last())"> -</xsl:if>
</xsl:template>