Counting nodes with certain attribute values in XSLT

Paul Reiners picture Paul Reiners · Jun 21, 2010 · Viewed 8.1k times · Source

Suppose I have some XML like this:

    <section name="SampleSection">
        <item name="ScoredItem1">
            <attributes>
                <scored data_type="boolean" value="true"/>
            </attributes>
        </item>
        <item name="UnscoredItem1">
            <attributes>
                <scored data_type="boolean" value="false"/>
            </attributes>
        </item>
        <item key="(3272fbb5:22)" name="ScoredItem2">
            <attributes>
                <scored data_type="boolean" value="true"/>
            </attributes>
        </item>
    </section>

Now, I know, using XSLT, I can count the items that have a scored attribute like this:

<xsl:variable name="scoredItems" select="item/attributes/scored"/>
<xsl:value-of select="count($scoredItems)"/>

This will give me a value of 3, of course.

Suppose I only want to count those items for which scored is true. How do I do that using XSLT? (This should return a value of 2 for this example.

Answer

Paul Reiners picture Paul Reiners · Jun 21, 2010

Do it like this:

<xsl:variable name="scoredItems"
              select=
                  "item/attributes/scored[@value='true']"/>