[xsl] Numbering new nodes using consecutive integers

Subject: [xsl] Numbering new nodes using consecutive integers
From: Michael Ludwig <mlu@xxxxxxxxxxxxx>
Date: Fri, 27 Mar 2009 17:40:57 +0100
I added an additional level <G2> to a hierarchy of <Groups> and <G1>.
I want to assign numbers to the newly created <G2> nodes, which identify
them in the document. I managed to do so using <xsl:number>.

Now it would be perfect if the numbering was done as a strict sequence
of consecutive integers, meaning 1,2,3 instead of, say, 1,3,5.

Can this be done in 1.0, or 2.0, for that matter?

Michael Ludwig

milu@colinux:~/Werkstatt/xsl > expand -t2 groups.xml
<?xml version="1.0" encoding="iso-8859-1"?>
<Groups>
  <G1>
    <M>eins</M>
    <M>zwei</M>
    <M>drei</M>
    <M>vier</M>
    <M>f|nf</M>
    <M>sechs</M>
    <M>sieben</M>
  </G1>
  <G1>
    <M>acht</M>
    <M>neun</M>
    <M>zehn</M>
    <M>elf</M>
    <M>zwvlf</M>
  </G1>
</Groups>

milu@colinux:~/Werkstatt/xsl > expand -t2 groups.xsl
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform";>

  <xsl:output indent="yes" encoding="iso-8859-1"/>
  <xsl:strip-space elements="*"/>

  <!-- How many M elements per G2 element? -->
  <xsl:variable name="M-per-G2" select="2"/>

  <xsl:template match="G1">
    <xsl:copy>
      <xsl:apply-templates
        select="M[ position() mod $M-per-G2 = 1 ]" mode="group"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="M" mode="group">
    <G2><!-- I want this GR to be numbered sequentially. -->
      <xsl:attribute name="no">
        <xsl:number level="any"/>
      </xsl:attribute>
      <xsl:copy-of select="
        . | following-sibling::M[position() &lt; $M-per-G2]"/>
    </G2>
  </xsl:template>

  <xsl:template match="@*|node()"><!-- copy template -->
    <xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
  </xsl:template>

</xsl:stylesheet>

milu@colinux:~/Werkstatt/xsl > xsltproc groups.xsl groups.xml
<?xml version="1.0" encoding="iso-8859-1"?>
<Groups>
  <G1>
    <G2 no="1">
      <M>eins</M>
      <M>zwei</M>
    </G2>
    <G2 no="3">
      <M>drei</M>
      <M>vier</M>
    </G2>
    <G2 no="5">
      <M>f|nf</M>
      <M>sechs</M>
    </G2>
    <G2 no="7">
      <M>sieben</M>
    </G2>
  </G1>
  <G1>
    <G2 no="8">
      <M>acht</M>
      <M>neun</M>
    </G2>
    <G2 no="10">
      <M>zehn</M>
      <M>elf</M>
    </G2>
    <G2 no="12">
      <M>zwvlf</M>
    </G2>
  </G1>
</Groups>

Current Thread