4

Does contains() work for multiple words stored in a variable? Will the below one work? If it won't work, please help me with a solution.

<xsl:variable name="games" select="footballvolleyballchesscarrom"/>

<xsl:when test="contains($games,'chess,carrom')">CORRECT</xsl:when>
1
  • Your variable declaration isn't right. The string in @select must be quoted else would try to match an element with that name. Can you use XSLT-2.0? Using regular expressions for matching here would be simpler. Commented Jul 26, 2017 at 11:32

2 Answers 2

3

Assuming that you're looking to do a logical OR of substring containment...

First of all, this select is likely wrong1:

<xsl:variable name="games" select="footballvolleyballchesscarrom"/>

It's looking for an element named footballvolleyballchesscarrom. If you're trying to set games to the string footballvolleyballchesscarrom, change it to this:

<xsl:variable name="games" select="'footballvolleyballchesscarrom'"/>

Then, use either

XSLT 1.0

<xsl:when test="contains($games,'chess')
             or contains($games,'carrom')">CORRECT</xsl:when>

or

XSLT 2.0

<xsl:when test="matches($games,'chess|carrom')">CORRECT</xsl:when>

to test whether $games contains one of your multiple substrings.


1 If you really intended to select (possibly multiple) elements from the input XML here, there is another XSLT 2.0 option for testing the selected sequence against a set of possible values. If your input XML were, say,

<games>
  <game>football</game>
  <game>volleyball</game>
  <game>chess</game>
  <game>carrom</game>
</games>

then this template,

<xsl:template match="/">
  <xsl:variable name="games" select="//game"/>
  <xsl:if test="$games = ('chess','carrom')">CORRECT</xsl:if>
</xsl:template>

would output CORRECT because among the string values of the selected elements is at least one of chess or carrom.

Sign up to request clarification or add additional context in comments.

2 Comments

Of course, if your intended meaning was that it must contain both words, then you can replace "or" with "and" in the first solution. You didn't actually say what your requirements were.
Let's hear it from the OP, Dr. Kay :)
1

I think multiple variables will not work with contains method. As per the defination:

boolean contains(str1, str2)

str1 : A string that might contain the second argument. str2: A string that might be contained in the first argument.

Refer : https://msdn.microsoft.com/en-us/library/ms256195(v=vs.110).aspx

You can use or operator:

<xsl:when test="contains($games,'chess') or contains($games,'carrom')">CORRECT</xsl:when>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.