CriticalSab
CriticalSab

Reputation: 3

Add one to an xsl variable if there are one or more matching elements

I'm working on an xsl transform that is creating item numbers. It includes statements like this:

data-item-no="{$itemOffset + count(list//para)}"  

This is fine when I want to add the number of para elements to $itemOffset, but in this case the paras are all rolled up into a single item. I want to add 0 if there are no matches for "list//para" and 1 if there is one or more "list//para". How can I do this in xsl?

Upvotes: 0

Views: 36

Answers (1)

Ian Roberts
Ian Roberts

Reputation: 122414

In XSLT 2.0 you can make it explicit with

$itemOffset + (if (list//para) then 1 else 0)

In XSLT 1.0 make use of the fact that

  • an empty node set coerces to boolean false
  • a non-empty node set coerces to boolean true
  • boolean false coerces to the number 0
  • boolean true coerces to the number 1

So:

$itemOffset + boolean(list//para)

(the + operator implicitly coerces its arguments to be numbers)

Upvotes: 1

Related Questions