XSLT Conditional Count

Question

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.

XSLT:

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

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

</xsl:stylesheet>

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 ( 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', .))"/>
    
◀ Go back