3

I need to check if a particular value is there in a node list.

For now I am using for-each and I think this is not efficient.

<xsl:for-each select="$ChildList">
    <i><xsl:value-of select="current()"></xsl:value-of> and <xsl:value-of select="$thisProduct"></xsl:value-of></i><br/>
    <xsl:if test="string(current())=string($thisProduct)">
        <!--<xsl:variable name="flag" select="1"/>  -->
        <p><b>Found!</b>
</p>
    </xsl:if>
</xsl:for-each>

I shall like to get it in a single shot. How can I?

Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431
Kangkan
  • 15,267
  • 10
  • 70
  • 113

2 Answers2

3

When used in the way you are using it, current() is the same as . (See section 12.4). However, the purpose of current (broadly speaking) is to be able get the context node of the whole expression from within a predicate (where . represents the context of the predicate).

I imagine that the subtlety of this distinction may have caused some confusion.

This XPath expression will only succeed if the string value of the context node of the whole expression is the same as $thisProduct. This is obviously not what you desire:

$ChildList[string(current())=string($thisProduct)]

This expression will succeed if there is a node within $ChildList that has the same string value as $thisProduct.

$ChildList[string(.)=string($thisProduct)]

i.e. it looks through $ChildList for a node where the expression string(.)=string($thisProduct) is true.

Paul Butcher
  • 6,902
  • 28
  • 39
2

Use:

$thisProduct = $ChildList

In case thisProduct is defined to contain some atomic value (not a node-set or a sequence in XPath 2.0), and $ChildList is a node-set (or a sequence in XPath 2.0) then the above XPath expression evaluates to true() exactly when there is a node (or an item in XPath 2.0) in $ChildList whose string-value is equal to the string-value of $thisProduct.

You can use this short expression in the test attribute of any XSLT conditional instruction (xsl:if or xsl:when) or in the match pattern (the match attribute) of any xsl:template instruction.

Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431