Reputation: 93
consider my xml file:
<Record>
<AA bac="1" kjd="Same"/>
<BB dfd="02" dad="342"/>
<CC pod="11-A" dsd="11-B"/>
<CC pod="22-A" dsd="22-B"/>
<CC pod="33-A" dsd="33-B"/>
<CC pod="44-A" dsd="44-B"/>
<CC pod="55-A" dsd="55-B"/>
<CC pod="66-A" dsd="66-B"/>
<CC pod="77-A" dsd="77-B"/>
</Record>
I need to add another attribute (cnt) under the element CC, which is the counter for every 3 occurrences of CC. If it reaches 4, i need to increment it. I already did that part, but I need to get the last value of @cnt in CC and place it in one new (@cnt_1) of the attribute in AA.
Here is my xslt:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes" method="xml"/>
<xsl:strip-space elements="*"/>
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Record">
<xsl:copy>
<xsl:apply-templates select="* except CC"/>
<xsl:for-each-group select="CC" group-adjacent="(position() - 1) idiv 3">
<xsl:apply-templates select="current-group()">
<xsl:with-param name="group-pos" select="position()"/>
</xsl:apply-templates>
</xsl:for-each-group>
</xsl:copy>
</xsl:template>
<xsl:template match="CC">
<xsl:param name="group-pos"/>
<CC cnt="{$group-pos}" seq="{position()}">
<xsl:apply-templates select="@*"/>
</CC>
</xsl:template>
<xsl:template match="CC/@*[not(normalize-space())]"/>
<xsl:template match="BB/@*[not(normalize-space())]" />
<xsl:template match="AA/@*[not(normalize-space())]" />
expected output:
<Record>
<AA cnt_1="3" bac="1" kjd="Same"/>
<BB dfd="02" dad="342"/>
<CC cnt="1" seq="1" pod="11-A" dsd="11-B"/>
<CC cnt="1" seq="2" pod="22-A" dsd="22-B"/>
<CC cnt="1" seq="3" pod="33-A" dsd="33-B"/>
<CC cnt="2" seq="1" pod="44-A" dsd="44-B"/>
<CC cnt="2" seq="2" pod="55-A" dsd="55-B"/>
<CC cnt="2" seq="3" pod="66-A" dsd="66-B"/>
<CC cnt="3" seq="1" pod="77-A" dsd="77-B"/>
</Record>
Thanks!
Upvotes: 0
Views: 81
Reputation: 117102
How about:
<xsl:template match="AA">
<xsl:copy>
<xsl:attribute name="cnt_1" select="ceiling(count(../CC ) div 3)"/>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
Upvotes: 1