Count XML nodes using XSLT but excluding certain nodes
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="assess开发者_StackOverflow社区ment">
<xsl:value-of select="count(.//item)"/>
</xsl:template>
</xsl:stylesheet>
How can I modify this code to exclude nested items?
Try this.
count(.//item[not(ancestor::item)])
Following your stylesheet, this
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<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.
精彩评论