Count records with a condition in XSLT

Afshin Moazami picture Afshin Moazami · Apr 26, 2013 · Viewed 13.7k times · Source

I have an xml with this structure:

<emails>
<record>
    <field name="host"><![CDATA[yahoo]]></field>
    <field name="user"><![CDATA[abc]]></field>
</record>
<record>
    <field name="host"><![CDATA[gmail]]></field>
    <field name="user"><![CDATA[abc]]></field>
</record>
<record>
    <field name="host"><![CDATA[yahoo]]></field>
    <field name="user"><![CDATA[cdx]]></field>
</record>
</emails>

And, I want to count the number of records where host = yahoo. I know that I need to use count(), but I couldn't figure out how.

Answer

Tim C picture Tim C · Apr 27, 2013

Assuming you were positioned on the emails element, this is the expression you probably want

<xsl:value-of select="count(record[field[@name='host']/text()='yahoo'])" />

For example, try this XSLT

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:template match="/emails">
      <xsl:value-of select="count(record[field[@name='host']/text()='yahoo'])" />
   </xsl:template>
</xsl:stylesheet>

Assuming your XML was well formed, and your CDATA tags were correctly formatted, it should output 3.