XSLT, 2nd Edition by Doug Tidwell

Get full access to XSLT, 2nd Edition and 60K+ other titles, with a free 10-day trial of O'Reilly.

There are also live events, courses curated by job role, and more.

[2.0] Conditional Expressions—if, then, and else

One of the less elegant features of XSLT is its if-then-else logic. If I want to test one condition (a simple if ), I use . If I want to change that to test more than one condition or add an else case, I have to use , , and . (We cover those elements in Chapter 5.) XPath 2.0 gives us the extremely useful if operator. We can now do if-then-else logic inside the XPath expression itself.

For comparison, here’s how we do things in XSLT 1.0:

      
An example of if-then-else logic in XSLT 1.0: 

 If $x is larger than 10, print 'Big', 
 otherwise print 'Little' 

  Big  Little   
  

We look at the value of $x and write Big if it’s larger than 10; otherwise, we write Little . Pretty simple stuff, but the element takes up 8 lines here. To do the same thing in XSLT 2.0, it’s much simpler:

Get XSLT, 2nd Edition 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.