Raj
Raj

Reputation: 343

How to check variable against a set of values in XSLT 1.0?

I have the following condition to test

<xsl:if test="   $Occupation='5' 
              or $Occupation='7'  
              or $Occupation='N' 
              or $Occupation='M' 
              or $Occupation='J' 
              or $Occupation='V' 
              or $Occupation='W'">
  <xsl:value-of select="'Accounts'"/>        
</xsl:if>

Is there a way to check like this?

<xsl:if test="$occupation contains('5','7','N','W','J','M')">

Upvotes: 2

Views: 3641

Answers (4)

kjhughes
kjhughes

Reputation: 111491

XSLT 2.0

You can do this much more cleanly in XSLT 2.0:

$occupation = ('5','7','N','M','J','V','W')

XSLT 1.0

For single-character value cases such as yours, this XPath 1.0 expression,

translate($occupation,'7NMJVW','555555')='5'

will return true when $occupation is 5, 7, N, M, J, V, or W as requested.

For single- or multi-character value cases, see Thomas W's answer or michael.hor257k's answer, which employ a technique often used to test @class attribute values safely:

contains(concat(" ", normalize-space(@class), " "), " target ")]

Upvotes: 0

Stefan Hegny
Stefan Hegny

Reputation: 2177

The other way round might work...

<xsl:if test="contains('57NWJM',$Occupation)">

Upvotes: 0

Thomas W
Thomas W

Reputation: 15361

Assuming everything in your list is a single character:

<xsl:if test="string-length($occupation) = 1 and contains('57NWJM', $occupation)">
    <xsl:value-of select="'Accounts'"/>        
</xsl:if>

If the entries are longer than one character, you can use a separation character. This character must of course not appear in any of the values in your list. With a space as separation character, things might look like:

<xsl:if test="not(contains($occupation, ' ')) and contains(' foo bar baz ', concat(' ', $occupation, ' '))">
    <xsl:value-of select="'Accounts'"/>        
</xsl:if>

Make sure you don't forget those padding spaces before foo and after baz.

Upvotes: 4

michael.hor257k
michael.hor257k

Reputation: 116959

You could use:

<xsl:if test="contains('57NMJ', $Occupation)">

but this would also return true when $Occupation = "7N", for example.

To protect against that, you can use:

<xsl:if test="contains('|5|7|N|M|J|', concat('|', $Occupation, '|'))">

Upvotes: 3

Related Questions