tags:

views:

45

answers:

2

I have the following XML:

<assessment>
    <section>
        <item name="Item1"/>
        <item name="Item2"/>
        <item name="Item3">
            <attributes>
                <item_references>
                    <item_reference>
                        <attributes>
                            <item name="Item3.1">
                                <item name="Item3.1.1"/>
                            </item>
                        </attributes>
                    </item_reference>
                </item_references>
            </attributes>
        </item>
    </section>
</assessment>

Using XSLT, I want to count the number of items, but not count those items that are nested within items. In this case, I want to count Item1, Item2, and Item 3, but not Item3.1 or Item3.1.1. So, in this case, the answer should be 3 (and not 5).

I have the following code that counts items, but doesn't leave out nested items:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:template match="assessment">
        <xsl:value-of select="count(.//item)"/>
    </xsl:template>
</xsl:stylesheet>

How can I modify this code to exclude nested items?

+2  A: 

Try this.

count(.//item[not(ancestor::item)])

soconnor
@soconnor: Do not recommend descendant axis when it's not really necessary. Also, if you are a father you know your sons.
Alejandro
A: 

Following your stylesheet, this

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;
    <xsl:output method="text"/>
    <xsl:template match="assessment">
        <xsl:value-of select="count(*/item)"/>
    </xsl:template>
</xsl:stylesheet>

Result:

3

Note: You could also match section element. Avoid descendant axis when possible.

Alejandro