XSLT Conditional Count


new to this site. Hoping someone can help me figure out why my code is not working. I used some other posts on the subject from this site to get this close, but can't see my error.


<!-- Keyset based on the Subject (Part Number) -->
<xsl:key name="key_PartNumber" match="Subject" use="."/>

<xsl:template match="/">
      <!-- Do for each unique Subject (Part Number) -->
      <xsl:for-each select="//Markup/Subject[generate-id() = generate-id(key('key_PartNumber', .)[1])]">
            <xsl:attribute name="Part_Number">
               <xsl:value-of select="."/>
            <xsl:attribute name="Count">
               <xsl:value-of select="count(//Markup[Subject=.])"/>


When I run my transform, I always get counts of 0. Below is a screenshot of both the sample xml file, as well as the result of an xpath query that are getting the correct result. SAMPLE XML with XPATH Result

Show source
| xml   | xslt   | xpath   2016-12-22 20:12 2 Answers

Answers to XSLT Conditional Count ( 2 )

  1. 2016-12-22 20:12

    Replace [Subject=.] by [Subject=current()]. The context item changes within a predicate.

  2. 2016-12-22 21:12

    As already explained, the problem with your approach is that the abbreviation . when used inside a predicate refers to the node preceding the predicate, not to the current context node: http://www.w3.org/TR/xpath/#predicates

    However, the correct solution here is to reuse the key:

    <xsl:value-of select="count(key('key_PartNumber', .))"/>

Leave a reply to - XSLT Conditional Count

◀ Go back