XML technologies / XSLT / XSLT Cookbook / Selecting and traversing / Processing nodes by position

(Excerpt from “XSLT Kochbuch” by Sal Mangano)

Problem

You want to process nodes in an order determined by their position in a document or node set.

Solution

Use xsl:sort with the selection set to function position( ) or last( ). The simplest application processes nodes in reverse document order:

<xsl:apply-templates>
  <xsl:sort select="position( )" order="descending" data-type="number"/>
</xsl:apply-templates>

or:

<xsl:for-each select="*">
  <xsl:sort select="position( )" order="descending" data-type="number"/>
  <!-- ... -->
</xsl:for-each>

Another common variant traverses a node set as though it were a matrix with a fixed number of columns. Here, all nodes in the first column are processed, then the second, then the third:

<xsl:for-each select="*">
  <xsl:sort select="(position( ) - 1) mod 3" />
  <!-- ... -->
</xsl:for-each>

Or, perhaps more cleanly:

<xsl:for-each select="*[position( ) mod 3 = 1]">
  <xsl:apply-templates select=". | following-sibling::*[position( ) &lt; 3]" />
</xsl:for-each>

Sometimes you need position( ) to separate the first node from the rest of a node set. This enables recursion to perform complex aggregation operations on a document. I call this idiom recursive-aggregation. Its abstract form is:

<xsl:template name="aggregation">
  <xsl:param name="node-set"/>
  <xsl:choose>
    <xsl:when test="$node-set">
      <!--Wir berechnen eine Funktion des ersten Elements, die einen Wert erzeugt, den wir vereinigen wollen. Die Funktion kann vom Typ des Elements abhängen (d.h. sie kann polymorph sein) -->
      <xsl:variable name="first">
        <xsl:apply-templates select="$node-set[1]" mode="calc"/>
      </xsl:variable>
      <!--Wir verarbeiten die verbleibenden Knoten rekursiv mit Hilfe von position( ) -->
      <xsl:variable name="rest">
        <xsl:call-template name="aggregation">
          <xsl:with-param name="node-set" select="$node-set[position( )!=1]"/>
        </xsl:call-template>
      </xsl:variable>
      <!-- Wir führen eine Vereinigungsoperation durch. Diese muss keinen Aufruf an ein Template erfordern. Beispielsweise könnte es sein: $first + $rest oder $first * $rest oder concat($first,$rest) usw. -->
      <xsl:call-template name="aggregate-func">
        <xsl:with-param name="a" select="$first"/>
        <xsl:with-param name="b" select="$rest"/>
      </xsl:call-template>
    </xsl:when>
    <!-- Hier sollte IDENTITY-VALUE durch den Gleichheitswert unter aggregate-func ersetzt werden. Zum Beispiel ist 0 der Gleichheitswert für die Addition, 1 ist der Gleichheitswert für die Subtraktion, "" ist der Gleichheitswert für die Verkettung usw. -->
    <xsl:otherwise>IDENTITY-VALUE</xsl:otherwise>
</xsl:template>

Discussion

XSLT naturally tends to process nodes in document order, equivalent to processing them in order of position. Thus, the following fragments are equivalent; the sort is redundant:

<xsl:for-each select="*">
  <xsl:sort select="position( )"/>
  <!-- ... -->
</xsl:for-each>

<xsl:for-each select="*">
  <!-- ... -->
</xsl:for-each>

You can format your organization chart (orgchart.xml) as a two-column report using a variation of this approach (see the next two examples).

Example: The columns-orgchat.xslt stylesheet.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text" />
  <xsl:strip-space elements="*"/>
  <xsl:template match="employee[employee]">
    <xsl:value-of select="@name"/>
    <xsl:text>&#xA;</xsl:text>
    <xsl:call-template name="dup">
      <xsl:with-param name="input" select=" '-' "/>
      <xsl:with-param name="count" select="80"/>
    </xsl:call-template>
    <xsl:text>&#xA;</xsl:text>
    <xsl:for-each select="employee[(position() - 1) mod 2 = 0]">
      <xsl:value-of select="@name"/>
      <xsl:call-template name="dup">
        <xsl:with-param name="input" select=" ' ' "/>
        <xsl:with-param name="count" select="40 - string-length(@name)"/>
      </xsl:call-template>
      <xsl:value-of select="following-sibling::*[1]/@name"/>
      <xsl:text>&#xA;</xsl:text>
    </xsl:for-each>
    <xsl:text>&#xA;</xsl:text>
    <xsl:apply-templates/>
  </xsl:template>
  <xsl:template name="dup">
    <xsl:param name="input"/>
    <xsl:param name="count" select="1"/>
    <xsl:choose>
      <xsl:when test="not($count) or not($input)"/>
      <xsl:when test="$count = 1">
        <xsl:value-of select="$input"/>
      </xsl:when>
      <xsl:otherwise>
        <xsl:if test="$count mod 2">
          <xsl:value-of select="$input"/>
        </xsl:if>
        <xsl:call-template name="dup">
          <xsl:with-param name="input" select="concat($input,$input)"/>
          <xsl:with-param name="count" select="floor($count div 2)"/>
        </xsl:call-template>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>
</xsl:stylesheet>

Example: Output.

Jil Michel
-------------------------------------------------------------------------------
Nancy Pratt                                  Jane Doe
Mike Rosenbaum

Nancy Pratt
-------------------------------------------------------------------------------
Phill McKraken                             Ima Little

Ima Little
-------------------------------------------------------------------------------
Betsy Ross

Jane Doe
-------------------------------------------------------------------------------
Walter H. Potter                           Wendy B.K. McDonald

Wendy B.K. McDonald
-------------------------------------------------------------------------------
Craig F. Frye                                Hardy Hamburg
Rich Shaker

Mike Rosenbaum
-------------------------------------------------------------------------------
Cindy Post-Kellog                        Oscar A. Winner

Cindy Post-Kellog
-------------------------------------------------------------------------------
Allen Bran                                    Frank N. Berry
Jack Apple

Oscar A. Winner
-------------------------------------------------------------------------------
Jack Nicklaus                               Tom Hanks
Susan Sarandon

Jack Nicklaus
-------------------------------------------------------------------------------
R.P. McMurphy

Tom Hanks
-------------------------------------------------------------------------------
Forrest Gump                              Andrew Beckett

Susan Sarandon
-------------------------------------------------------------------------------
Helen Prejean

One recursive aggregation example is a stylesheet computing total commission for salespeople whose commission depends on total sales across all products, as shown in the next two examples.

Example: The Total-commission.xslt stylesheet.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text"/>
  <xsl:template match="salesBySalesperson">
    <xsl:text>Gesamtprovision = </xsl:text>
    <xsl:call-template name="total-commission">
      <xsl:with-param name="salespeople" select="*"/>
    </xsl:call-template>
  </xsl:template>
  <!-- Standardmäßig erhalten Vertreter 2% Provision und keine Grundvergütung -->
  <xsl:template match="salesperson" mode="commission">
    <xsl:value-of select="0.02 * sum(product/@totalSales)"/>
  </xsl:template>
  <!-- Vertreter mit with seniority &gt; 4 erhalten $10000.00 Grundvergütung + 0.5% Provision -->
  <xsl:template match="salesperson[@seniority &gt; 4]" mode="commission" priority="1">
    <xsl:value-of select="10000.00 + 0.05 * sum(product/@totalSales)"/>
  </xsl:template>
  <!-- Vertreter mit seniority &gt; 8 erhalten (seniority * $2000.00) Grundvergütung + 0.8% Provision -->
  <xsl:template match="salesperson[@seniority &gt; 8]" mode="commission" priority="2">
    <xsl:value-of select="@seniority * 2000.00 + 0.08 * sum(product/@totalSales)"/>
  </xsl:template>
  <xsl:template name="total-commission">
    <xsl:param name="salespeople"/>
    <xsl:choose>
      <xsl:when test="$salespeople">
        <xsl:variable name="first">
          <xsl:apply-templates select="$salespeople[1]" mode="commission"/>
        </xsl:variable>
        <xsl:variable name="rest">
          <xsl:call-template name="total-commission">
            <xsl:with-param name="salespeople" select="$salespeople[position()!=1]"/>
          </xsl:call-template>
        </xsl:variable>
        <xsl:value-of select="$first + $rest"/>
      </xsl:when>
      <xsl:otherwise>0</xsl:otherwise>
    </xsl:choose>
  </xsl:template>
</xsl:stylesheet>

Example: Output.

Gesamtprovision = 471315

XSLT 2.0

In 2.0, you can combine functions and templates to avoid recursion while retaining template pattern matching to calculate commissions:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:ckbk="http://www.oreilly.com/catalog/xsltckbk">
  <xsl:output method="text"/>
  <xsl:template match="salesBySalesperson">
    <xsl:text>Gesamtprovision = </xsl:text>
    <xsl:value-of select="ckbk:total-commission(*)"/>
  </xsl:template>
  <!-- Standardmäßig erhalten Vertreter 2% Provision und keine Grundvergütung -->
  <xsl:template match="salesperson" mode="commission" as="xs:double">
    <xsl:sequence select="0.02 * sum(product/@totalSales)"/>
  </xsl:template>
  <!-- Vertreter mit seniority &gt; 4 erhalten $10000.00 Grundvergütung + 0.5% Provision -->
  <xsl:template match="salesperson[@seniority &gt; 4]" mode="commission" priority="1" as="xs:double">
    <xsl:sequence select="10000.00 + 0.05 * sum(product/@totalSales)"/>
  </xsl:template>
  <!-- Vertreter mit seniority &gt; 8 erhalten (seniority * $2000.00) Grundvergütung + 0.8% Provision -->
  <xsl:template match="salesperson[@seniority &gt; 8]" mode="commission" priority="2" as="xs:double">
    <xsl:sequence select="@seniority * 2000.00 + 0.08 * sum(product/@totalSales)"/>
  </xsl:template>
  <xsl:function name="ckbk:total-commission" as="xs:double">
    <xsl:param name="salespeople" as="node( )*"/>
    <xsl:sequence select="sum(for $s in $salespeople return ckbk:commission($s))"/>
  </xsl:function>
  <xsl:function name="ckbk:commission" as="xs:double">
    <xsl:param name="salesperson" as="node( )"/>
    <xsl:apply-templates select="$salesperson" mode="commission"/>
</xsl:function>

See also

Michael Kay gives a useful recursive aggregation example on page 535 of XSLT Programmer's Reference (Wrox Press, 2001), calculating total area for different shapes whose area formula depends on their type.

Jeni Tennison’s XSLT and XPath on the Edge (M&T Books, 2001) also provides recursive aggregation examples and alternative methods for similar processing.

  

 

 

 

back to top