Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count records with a condition in XSLT

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.

like image 749
Afshin Moazami Avatar asked Apr 26 '13 21:04

Afshin Moazami


People also ask

How do I count records in XSLT?

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'.

How do I count characters in XSLT?

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.

What is number () in XSLT?

Specifies the format pattern. Here are some of the characters used in the formatting pattern: 0 (Digit) # (Digit, zero shows as absent)

Can we use contains in XSLT?

contains() Function — Determines if the first argument string contains the second.


1 Answers

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.

like image 134
Tim C Avatar answered Sep 18 '22 13:09

Tim C