Tuesday, 19 July 2016

XSL - Check if item is contained in a list

Use the below sample if you want to check if an item is contained in a list.
This sample is using XSL and XPATH with XML input.
In the below sample:
<!-- .xsl file -->

<!-- List of items to be checked against -->
<xsl:variable name="students" select="'Jon Tom Ana Ben'" />

<!-- Item to be checked if contained in list -->
<xsl:variable name="classTopper" select="'Ana'" />

<!-- Alternately the item can be dynamically taken from the xml input file as below -->
<!-- <xsl:variable name="classTopper" select="/root/@topper" /> -->

<!-- Check if class topper is in the students list -->
<xsl:if test="
  contains(
    concat(' ', $students, ' '),
    concat(' ', $classTopper, ' ')
  )
">
  <xsl:value-of select="concat('Student ', $classTopper, ' is in the students list.')" />
</xsl:if>

Note: Here space is used as separator in the list. You can replace with something else like a pipe "|". In that case, the concat in contains() will be like:
concat ('|', $list, '|') ...

No comments:

Post a Comment