Reputation: 1159
I use a template as
<xsl:template name="myTemplate">
and I need to count the amount of level nodes whose values are "ON" and "OFF".
The final report that I want to have:
this file contains three "ON" values and two "OFF" values.
Look at a part of my xml file.
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml:stylesheet type='text/xsl' href='view.xsl'?>
<DOC>
<show>VIEW<show/>
<Entry>
<light>ae</light>
<level>ON</level>
</Entry>
<Entry>
<light>by</light>
<level>OFF</level>
</Entry>
<Entry>
<light>ac</light>
<level>OFF</level>
</Entry>
<Entry>
<light>pc</light>
<level>ON</level>
</Entry>
<Entry>
<light>tc</light>
<level>ON</level>
</Entry>
Thank for your help
Upvotes: 0
Views: 61
Reputation: 459
The question is to count and spell out the numbers i.e two, three. Please find below XSLT and the list of format values to be used in the link given.
<?xml version='1.0'?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:template match="DOC">
<xsl:text>this file contains </xsl:text>
<xsl:number value="count(descendant::level[(.)='ON'])" format="w"/>
<xsl:text> "ON" values and </xsl:text>
<xsl:number value="count(descendant::level[(.)='OFF'])" format="w"/>
<xsl:text> "OFF" values.</xsl:text>
</xsl:template>
</xsl:stylesheet>
Please refer the below documentation for format: http://www.w3.org/TR/xslt20/#element-number
Upvotes: 0
Reputation: 3738
These simple XPaths will do the trick:
count(/*/*/level[. = 'ON'])
and
count(/*/*/level[. = 'OFF'])
For verification, when this XSLT:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output omit-xml-declaration="yes" indent="yes" method="text"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/*">
<xsl:text>The number of ON nodes is: </xsl:text>
<xsl:value-of select="count(/*/*/level[. = 'ON'])"/>
<xsl:text/>
<xsl:text>The number of OFF nodes is: </xsl:text>
<xsl:value-of select="count(/*/*/level[. = 'OFF'])"/>
</xsl:template>
</xsl:stylesheet>
...is applied against the provided XML:
<DOC>
<show>VIEW</show>
<Entry>
<light>ae</light>
<level>ON</level>
</Entry>
<Entry>
<light>by</light>
<level>OFF</level>
</Entry>
<Entry>
<light>ac</light>
<level>OFF</level>
</Entry>
<Entry>
<light>pc</light>
<level>ON</level>
</Entry>
<Entry>
<light>nc</light>
<level>ON</level>
</Entry>
</DOC>
...the wanted result is produced:
The number of ON nodes is: 3
The number of OFF nodes is: 2
Upvotes: 1