Connecting Tech Pros Worldwide Forums | Help | Site Map

Counter in XSLT

Newbie
 
Join Date: Dec 2008
Posts: 5
#1: 3 Weeks Ago
Hi All,

I'm having trouble counting the number of occurring nodes from my input XML.

I have this input:
Expand|Select|Wrap|Line Numbers
  1. <root>
  2.   <level1>
  3.     <countMeIn1/>
  4.   <level1>
  5.   <level1>
  6.     <countMeIn2/>
  7.   <level1>
  8.   <level1>
  9.     <countMeIn3/>
  10.     <countMeIn4/>
  11.     <countMeIn5/>
  12.   <level1>
  13. </root>
  14.  
And my desired output is:

Expand|Select|Wrap|Line Numbers
  1. <root>
  2.   <countMeIn count="1"/>
  3.   <countMeIn count="2"/>
  4.   <countMeIn count="3"/>
  5.   <countMeIn count="4"/>
  6.   <countMeIn count="5"/>
  7. </root>
  8.  
I have tried the position() function but that only renders an incremented number for 3,4 and 5.

Any help would be greatly appreciated.



Dormilich's Avatar
Moderator
 
Join Date: Aug 2008
Location: Leipzig, Germany
Posts: 3,648
#2: 3 Weeks Ago

re: Counter in XSLT


Quote:

Originally Posted by blacksab View Post

I'm having trouble counting the number of occurring nodes from my input XML.

could you explain, how you want to count the nodes, because I can’t follow your calculation.
Newbie
 
Join Date: Dec 2008
Posts: 5
#3: 3 Weeks Ago

re: Counter in XSLT


Hi Dormilich,

I explained my input badly. In my input XML I have several nodes named countMeIn. I want to do a sequential count of the included countMeIn nodes in the output XML
Expand|Select|Wrap|Line Numbers
  1.  <root>
  2.    <level1>
  3.      <countMeIn/> <!-- Want an attribute named count="1" for this node-->
  4.    <level1>
  5.    <level1>
  6.      <countMeIn/> <!-- Want an attribute named count="2" for this node-->
  7.    <level1>
  8.    <level1>
  9.      <countMeIn/> <!-- Want an attribute named count="3" for this node-->
  10.      <countMeIn/> <!-- Want an attribute named count="4" for this node-->
  11.      <countMeIn/> <!-- Want an attribute named count="5" for this node-->
  12.    <level1>
  13.  </root>
  14.  
Dormilich's Avatar
Moderator
 
Join Date: Aug 2008
Location: Leipzig, Germany
Posts: 3,648
#4: 3 Weeks Ago

re: Counter in XSLT


after some thinking I came up with 2 ideas
1. use the DOM
2. use XSLT twice, the first one is only for grabbing the <CountMeIn> nodes, the second one you can use to make the count attribute.
Newbie
 
Join Date: Dec 2008
Posts: 5
#5: 3 Weeks Ago

re: Counter in XSLT


This is solved:

This node to do the assignment to counter:
<xsl:variable name="counter">
<xsl:number level="any" count="countMeIn"/>
</xsl:variable>

And then this node to output the value as an attribute:
<xsl:attribute name="line">
<xsl:value-of select="$counter"/>
</xsl:attribute>

This solution was also given on another thread in this forum.

Thank you for your input.
Reply