Wilvasini
Wilvasini

Reputation: 163

find out the count of current element within its parent using xslt

<a>
  <b/>
  <b/>
  <c/>
</a>

I want to find out the count of the current element that i am parsing when my node is in that current element and i am not aware the element names as well.

I tried :

<xsl:for-each select="a">
   <counter localName="{local-name()}" count="{count(node()/*)}"/>
</xsl:for-each>

Output I expect:

 <counter localName="b" count="2"/>
 <counter localName="b" count="2"/>
 <counter localName="c" count="1"/>

this gives a wrong output how do i achieve it ?

Upvotes: 0

Views: 121

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 116992

I am guessing you want to do:

<xsl:template match="/a">
    <root>
        <xsl:for-each select="*">
            <counter localName="{local-name()}" count="{count(../*[local-name()=local-name(current())])}"/>
        </xsl:for-each>
    </root>
</xsl:template>

This will return:

<root>
  <counter localName="b" count="2"/>
  <counter localName="b" count="2"/>
  <counter localName="c" count="1"/>
</root>

Do note that by using local-name() you are purposefully ignoring the namespace. Thus the result will be the same if the input happens to be:

<a>
  <b/>
  <ns1:b xmlns:b="http://example.com/b"/>
  <c/>
</a>

although clearly the two b nodes counted together have nothing in common except by coincidence.

Upvotes: 2

Related Questions