Chapter 4. Using Logic

The declarative nature of XSLT programming and the complex nature of many XML source documents often leads to stylesheets that make extensive use of template rules.

In some cases, however, you will want to use a more imperative style of programming, exercising specific control over the processor. One of these cases is when you want to use logic to test for simple or complex conditions, and direct processing accordingly. Another is when the source data is repetitive in nature, and the most straightforward thing to do is iterate over it.

In this short chapter you'll do the following:

  • Learn more details about how you can control processing using <xsl:if>, <xsl:choose>, and conditional expressions in XPath.

  • Learn when best to use <xsl:for-each> for iterative processing, rather than <xsl:apply-templates>.

  • Apply the <xsl:attribute-set> declaration to define attribute values to be used in creating tabular output in XHTML.

  • Process CDATA sections to display code examples that illustrate the use of XSLT elements.

Conditional Processing

There are two instructions in XSLT that enable you to perform actions based on data values conditionally. The <xsl:if> instruction provides a simple test, with a single outcome if the test is positive; the <xsl:choose> instruction supports the selection of one choice when there are several possibilities. They are conceptually similar to the if and case constructs you have encountered in other languages.

A Simple Choice

The <xsl:if> instruction ...

Get Beginning XSLT and XPath: Transforming XML Documents and Data now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.