Re: [xsl] hierarchic counting in flat structures

Subject: Re: [xsl] hierarchic counting in flat structures
From: "G. Ken Holman" <gkholman@xxxxxxxxxxxxxxxxxxxx>
Date: Fri, 02 Nov 2012 07:31:15 -0400
At 2012-11-02 11:16 +0100, Norbert Heidbrink wrote:
Hi everyone,

given a structure like

<H3></H3>
  <H4></H4>
  <H4></H4>
<H3></H3>
  <H4></H4>
<H3></H3>
  <H4></H4>
  <H4></H4>
  <H4></H4>

I would like to number the H4, re-starting on every H3.
So the output is something like this:

H3: 1
  H4: 1
  H4: 2
H3: 2
  H4: 1
H3: 3
  H4: 1
  H4: 2
  H4: 3

The following xsl does the job, but I wonder if this solution is really
effective and elegant.

<xsl:template match="H4">
  <xsl:text>&#x0a;  H4: </xsl:text>
  <xsl:variable name="myH3" select="preceding-sibling::H3[1]" />
  <xsl:value-of select="1 + count(preceding-sibling::H4[preceding-
sibling::H3 = $myH3])" />

The above will be performing a very inefficient comparison of the text values of nodes, and it will fail when you co-incidentally have the same value for more than one node.

I think you want this (which I don't have the time to throw into a quick
test):

<xsl:template match="H4">
  <xsl:text>&#x0a;  H4: </xsl:text>
  <xsl:value-of select="1 + count( preceding-sibling::H4 ) -
              count( preceding-sibling::H3[1]/preceding-sibling::H4 )"/
</xsl:template>

One of the exercises on day 2 of my class brings
this approach to axes to light by mimicking the
conversion of scanned legacy content into a structure.

In a sentence the above is determining:

  "the difference between the count of all preceding sibling H4's
   and the count of the H4's that precede the closest preceding H3"

... which will give you the count of H4's up to
to the closest preceding H3.  Then add 1 for the given H4.

A similar technique is done when analyzing table column position differences.

</xsl:template>

Are there better ways to solve my problem?

I think my suggestion is better because it is simply counting nodes in the tree and it is not evaluating equality expressions with the text values of subtrees.

I hope this helps.

. . . . . . . . . Ken


-- Contact us for world-wide XML consulting and instructor-led training Free 5-hour lecture: http://www.CraneSoftwrights.com/links/udemy.htm Crane Softwrights Ltd. http://www.CraneSoftwrights.com/s/ G. Ken Holman mailto:gkholman@xxxxxxxxxxxxxxxxxxxx Google+ profile: https://plus.google.com/116832879756988317389/about Legal business disclaimers: http://www.CraneSoftwrights.com/legal

Current Thread