Larry
Larry

Reputation: 989

XSL Looping: how to loop where node name increments

How would one loop thru a set of nodes, where the node name has a numeric number and the number increments as in a series?

ex:

<nodes>
  <node1>
  <node2>
  ...
  <node10>
</nodes>

Upvotes: 0

Views: 890

Answers (3)

Tomalak
Tomalak

Reputation: 338228

<xsl:template match="nodes">
  <xsl:apply-templates select="*">
    <!-- the xsl:sort is redundant if the input already is in correct order -->
    <xsl:sort select="substring-after(name(), 'node')" data-type="number" />
  </xsl:apply-templates>
</xsl:template>

<xsl:template match="nodes/*">
  <!-- whatever -->
</xsl:template>

Upvotes: 0

ChaosPandion
ChaosPandion

Reputation: 78272

Unless I am missing something completely what you need is as simple as this.

<xsl:template match="nodes">
    <xsl:for-each select="*">
        <!-- Do what you want with each node. -->
    </xsl:for-each>
</xsl:template>

Upvotes: 2

xcut
xcut

Reputation: 6349

A recursive named template can do that:

<xsl:template name="processNode">
  <xsl:param name="current" select="1"/> 
  <xsl:variable name="currentNode" select="*[local-name() = concat('node', $current)]"/>

  <xsl:if test="$currentNode">
    <!-- Process me -->
    <xsl:call-template name="processNode">
      <xsl:with-param name="current" select="$current + 1"/>
    </xsl:call-template>
  </xsl:if>
</xsl:template>

Or if you don't care about order, just a normal template:

<xsl:template match="*[starts-with(local-name(), 'node')]">
</xsl:template>

Upvotes: 1

Related Questions