Question

I am new to fairly new to XML/XSL so i'll try to be as descriptive as possible. I have an XML element that I need to populate a value with that gives a number that is incremented each time the element is found.

Here is what I have so far:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:variable name="count">
    <xsl:number level="any" value="position()"/>
</xsl:variable>

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

<xsl:template name="index">
    <xsl:param name="counter" select="''"/>
    <xsl:value-of select="$count"/>
</xsl:template>

<xsl:template match="//file_item_nbr">
    <file_item_nbr>
        <xsl:call-template name="index">
            <xsl:with-param name="counter" select="''">
                <!--<xsl:value-of select="$count + 1"/-->
            </xsl:with-param>
        </xsl:call-template>
    </file_item_nbr>
</xsl:template>
</xsl:stylesheet>

The XML data has a variety of file_item_nbr tags nested within other elements. that's why the template matches on all file_item_nbr elements using the //file_item_nbr xpath.

How can I increment the number for each file_item_nbr?

Was it helpful?

Solution

You're on the right track with <xsl:number level="any"/>, but you need to evaluate this instruction each time you want it. At present you're evaluating it once, storing the result in a variable, and then inserting that precomputed value every time.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

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

  <xsl:template match="file_item_nbr">
    <file_item_nbr>
      <xsl:number level="any"/>
    </file_item_nbr>
  </xsl:template>
</xsl:stylesheet>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top