4

Possible Duplicate:
XSLT expression to check if variable belongs to set of elements

Given a parameter, $name, what is a short and clean way to check if its value is equal to one of a finite number of values?

For example, say I wanted to merge the first 3 of these when tests because their contents were exactly the same.

<choose>
  <when test="$name='Alice'">
  <when test="$name='Bob'">
  <when test="$name='Cindy'">
  <when test="$name='Dave'">
  <otherwise>

Something like test="$name in ['Alice','Bob','Cindy']", except actually valid :P

Community
  • 1
  • 1
Svish
  • 152,914
  • 173
  • 462
  • 620

2 Answers2

9

With XSLT 2.0 it suffices to use $name = ('Alice', 'Bob', 'Cindy').

Martin Honnen
  • 160,499
  • 6
  • 90
  • 110
  • Nice! Love it. So much cleaner than the concat/contains and fn:tokenize/fn:index-of patterns. You should add this as an alternative answer for the duplicate as well: http://stackoverflow.com/q/1007018/39321 – Svish Oct 26 '12 at 12:24
  • Be aware that for testing if the value is NOT in the list, you use `not($name = ('Alice', 'Bob', 'Cindy'))`, because the result of `'Alice' != ('Alice', 'Bob', 'Cindy')` is true(). – iddo Sep 22 '17 at 16:15
2

Use (both in XSLT 1.0 and in XSLT 2.0):

contains('|Alice|Bob|Cindy|', concat('|', $name, '|'))

and, as Martin Honnen already mentioned, in XPath 2.0 (XSLT 2.0) only, one can simply write:

$name = ($seqOfNames)
Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431