Search code examples
xmlxsltxpathxslt-2.0xpath-2.0

XSLT: Check if a node is found in a nodelist


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?


Solution

  • 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.