Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XSLT: contains() for multiple strings

Tags:

xslt

I have a variable in XSLT called variable_name which I am trying to set to 1, if the Product in question has attributes with name A or B or both A & B.

<xsl:variable name="variable_name">
  <xsl:for-each select="product/attributes">
    <xsl:if test="@attributename='A' or @attributename='B'">
      <xsl:value-of select="1"/>
    </xsl:if>
  </xsl:for-each>
</xsl:variable>

Is there any way to match multiple strings using the if statement, as mine just matches if A is present or B is present. If both A & B are present, it does not set the variable to 1. Any help on this would be appreciated as I am a newbie in XSLT.

like image 799
chugh97 Avatar asked Feb 22 '10 10:02

chugh97


1 Answers

You can use xsl:choose statement, it's something like switch in common programming languages:

Example:

<xsl:variable name="variable_name">
  <xsl:for-each select="product/attributes">
  <xsl:choose>
    <xsl:when test="@attributename='A'">
      1
    </xsl:when>
    <xsl:when test=" @attributename='B'">
      1
    </xsl:when>
    <!--... add other options here-->
    <xsl:otherwise>1</xsl:otherwise>
  </xsl:choose>
  </xsl:for-each>
</xsl:variable> 

This will set new variable with name variable_name with the value of attribute product/attributes.

For more info ... http://www.w3schools.comwww.w3schools.com/xsl/el_choose.asp

EDIT: And another way (a little dirty) by OP's request:

<xsl:variable name="variable_name">
  <xsl:for-each select="product/attributes">
    <xsl:if test="contains(text(), 'A') or contains(text(), 'B')">
       1
    </xsl:if>
  </xsl:for-each>
</xsl:variable> 

It will be helpful if you provide the xml you're writing your xslt against.

like image 51
anthares Avatar answered Oct 06 '22 15:10

anthares