Johann
Johann

Reputation: 447

XSL - counting nodes depending on parents' position

I am trying to count nodes depending on the position of their parents.

This is an example :

<tbody>
    <row>
        <entry>L1C1</entry>
        <entry>L1C2</entry>
        <entry>L1C3</entry>
    </row>
    <row>
        <entry>L2C1</entry>
        <entry morerows="1">L2C2</entry>
        <entry>L2C3</entry>
    </row>
    <row>
        <entry>L3C1</entry>
        <entry>L3C3</entry>
    </row>
</tbody>

For each entry, I want to count the number of entry elements of preceding row elements whose attribute morerows is greater than a number which depends of the position of the row.

I have something like this:

<xsl:variable name="nbRows">
    <xsl:value-of select="count(ancestor::tbody/row)">
    </xsl:value-of>
</xsl:variable>

<xsl:value-of select="count(parent::row/preceding-sibling::row/entry[@morerows &gt; ($nbRows - count(current()/../preceding-sibling::row))])">
</xsl:variable>"/>

But as you can imagine, this does not work.

Can someone help me with this?

Upvotes: 0

Views: 2136

Answers (1)

MiMo
MiMo

Reputation: 11953

If I understood correctly the question this should do the job:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="row">
    <xsl:variable name="nRows" select="count(../row)"/>
    <xsl:variable name="precedingEntries" select="preceding-sibling::row/entry"/>
    <xsl:variable name="minMoreRows" select="$nRows - position() + 1"/>
    <n>
      <xsl:value-of select="count($precedingEntries[@morerows>=$minMoreRows])"/>
    </n>
  </xsl:template>

  <xsl:template match="/">
    <root>
      <xsl:apply-templates/>
    </root>
  </xsl:template>

</xsl:stylesheet>

The output - when applied to the example in the question - is:

<root>
    <n>0</n>
    <n>0</n>
    <n>1</n>
</root>

Upvotes: 2

Related Questions