Cover Image for XSLT xsl:apply-template
137 views

XSLT xsl:apply-template

In XSLT (Extensible Stylesheet Language Transformation), the xsl:apply-templates element is used to select and apply templates to nodes in the XML input document. XSLT is a language used to transform XML documents into different formats, such as HTML, plain text, or other XML structures.

The xsl:apply-templates element is a powerful and essential construct in XSLT, allowing you to define a set of rules (templates) for processing specific XML elements. When an XSLT processor encounters an xsl:apply-templates instruction during the transformation process, it looks for matching templates based on the context node in the input XML document and applies them to the corresponding nodes.

Syntax:

<xsl:apply-templates select="XPathExpression" />

Attributes:

  • select: This attribute specifies an XPath expression that defines the nodes to which the templates should be applied. The XPath expression is used to match nodes in the input XML document. If the select attribute is omitted, the default behavior is to select the child nodes of the current context node.

Example:

Consider the following XML input document:

<root>
  <item>
    <name>Item 1</name>
  </item>
  <item>
    <name>Item 2</name>
  </item>
</root>

Now, let’s define an XSLT stylesheet that uses the xsl:apply-templates element to transform the XML:

<!-- XSLT stylesheet -->
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <!-- Template for matching 'item' elements -->
  <xsl:template match="item">
    <p>
      Item: <xsl:value-of select="name" />
    </p>
  </xsl:template>

  <!-- Apply templates to the root node -->
  <xsl:template match="root">
    <html>
      <body>
        <xsl:apply-templates />
      </body>
    </html>
  </xsl:template>

</xsl:stylesheet>

In this example, we have two templates defined. The first template matches item elements and generates an HTML paragraph (<p>) for each matching node, displaying the value of the name element. The second template matches the root element and wraps the transformation output with an HTML structure.

When the XSLT processor processes the input XML document with the XSLT stylesheet, it will apply the templates based on the context nodes, producing the following output:

<html>
  <body>
    <p>Item: Item 1</p>
    <p>Item: Item 2</p>
  </body>
</html>

As you can see, the xsl:apply-templates element triggered the matching template for each item element in the XML, resulting in the desired transformation.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS