Search code examples
xmlxsltxpathxslt-1.0xslt-2.0

Assigning a string to a variable depending on condition in xslt


I want to assign a value to a variable if a particular attribute returns a particular value. In here I want to assign the value "young" to vaiable "person" if pr:all/[@pr:name=current()/@cx:name]/pr:properties/(@ls:middlename) is "cengie". Is that possible?

<xsl:variable
  name='person' select='pr:all/[@pr:name=current()/@cx:name]/pr:properties/(@ls:middlename)'>
</xsl:variable>

Solution

  • You can put any xslt code within an xsl:variable and the result will be assigned to the variable. In this case you could make use of an xsl:if to check your condition

    <xsl:variable name="person"> 
        <xsl:if test="pr:all[@pr:name=current()/@cx:name]/pr:properties[@ls:middlename='cengie']">
           <xsl:text>young</xsl:text>
        </xsl:if>
    </xsl:variable> 
    

    If you wanted an 'else' case here, you would use xsl:choose instead.