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.
The syntax says the count function tells the XSLT processor to count each time in which an XML tag found at the XPATH expression. It returns a number value that specifies the number of sequence elements contained in a sequence of items that passes by. The empty set of the count is returned to 'zero'.
Name. string-length() Function — Returns the number of characters in the string passed in as the argument to this function. If no argument is specified, the context node is converted to a string and the length of that string is returned.
Specifies the format pattern. Here are some of the characters used in the formatting pattern: 0 (Digit) # (Digit, zero shows as absent)
contains() Function — Determines if the first argument string contains the second.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With