Using XPath if-then-else

  • If your condition is very simple, and the processing you want to do as a result of it does not involve creating elements or attributes, then you can just use an if-then-else structure in XPath:
  • xsl:value-of select=count($docAuthors/author) gt 1'Authors: ''Author: ']]>

As we saw in the slide explaining how to use xsl:if, this slide shows a simple example of using the XPath if-then-else structure to pluralize author is there is more than one author element within docAuthor.

  • In this case the xsl:value-of element has a select attribute that contains an XPath if-then-else construct
  • The first condition, if, contains the XPath expression: count( $docAuthors/author ) gt 1.
  • This XPath expression starts by calling the function count(), which counts the number of items in its argument sequence. In this case, the argument to count() is the sequence of child author elements found in the variable $docAuthors (presumably the list of authors of the current document :-)
  • The XPath expression then asks the question is this (the value of the count() function) greater than one?. That’s what the gt means: greater than.
  • The answer to that question (is this (the value of the count() function) greater than one?) is either true() or false().
  • If the XPath expression after if is true, then the content following then is returned. Otherwise, the content following else is returned. In this example, if there is more than one author, then the condition will return the text: Authors: ; if not, then it will return the text: Author:

XPath if-then-else is useful for when your condition is very simple, and the processing you want to do as a result of it does not involve creating XML constructs like elements and attributes. Also, unlike xsl:if, XPath if-then-else allows you to process conditions for both the true() or false() evaluation of an XPath expression.

XSL Conditionals slide 04 of 6
© 2011 Martin Holmes This TEI-encoded XML file is available under the terms of the Creative Commons Attribution-ShareAlike 3.0 (Unported) license.