LC_123
LC_123

Reputation: 63

XSLT to get count of number of times value appears

I am trying to create a variable that will give me the count of times the value 1 shows up in my xml in pd:Eployee_Test:

Here is my XML:

<pd:Report_Data xmlns:wd="urn:com.playdate.report/TEST_REPORT">
    <pd:Report_Entry>
        <pd:Spouse_Test>0</pd:Spouse_Test>
        <pd:Employee_Test>1</pd:Employee_Test>
        <pd:DR-04-Last_Name>Jane</pd:DR-04-Last_Name>
        <pd:DR-05-First_Name>Smith</pd:DR-05-First_Name>
    </pd:Report_Entry>
    <pd:Report_Entry>
        <pd:Spouse_Test>0</pd:Spouse_Test>
        <pd:Employee_Test>1</pd:Employee_Test>
        <pd:DR-04-Last_Name>John</pd:DR-04-Last_Name>
        <pd:DR-05-First_Name>Smith</pd:DR-05-First_Name>
    </pd:Report_Entry>
    <pd:Report_Entry>
        <pd:Spouse_Test>0</pd:Spouse_Test>
        <pd:Employee_Test>1</pd:Employee_Test>
        <pd:DR-04-Last_Name>Jerry</pd:DR-04-Last_Name>
        <pd:DR-05-First_Name>Smith</pd:DR-05-First_Name>
    </pd:Report_Entry>

I am trying to return the count of 3 for each time the value = 1 appears thoughout the xml for pd:Employee_Test

Upvotes: 1

Views: 598

Answers (1)

Ian Roberts
Ian Roberts

Reputation: 122364

If this is just a one off then (assuming the right namespace bindings are in place in the stylesheet)

<xsl:variable name="numberOfOnes"
  select="count(/pd:Report_Data/pd:Report_Entry/pd:Employee_Test[. = '1'])" />

If it's something you're going to be doing repeatedly (e.g. count the 1s, then the 2s, etc.) then it would be more efficient to define a key

<xsl:key name="employeeTestByValue" match="pd:Employee_Test" use="." />

and then you can use count(key('employeeTestByValue', '1')) to count the number of occurrences for a given value.

Upvotes: 1

Related Questions