2
votes

yet another class take-home quiz I need help with to compare the position() return value against a parameter value as follows using XSLT 1.0. I have this simple XML below...

<Providers>
    <Company>
        <Name>Alpha</Name>
    </Company>

    <Company>
        <Name>Beta</Name>
    </Company>

    <Company>
        <Name>Omega</Name>
    </Company>
</Providers>

And I want to pass in a parameter with a numeric value designating which node level to insert a new element called Rating like this...

<Providers>
        <Company>
                <Name>Alpha</Name>
        </Company>

        <Company>
                <Name>Beta</Name>
                <Rating>Good</Rating>
        </Company>

        <Company>
                <Name>Omega</Name>
        </Company>
</Providers>

Here's my XSLT...

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes"/>
  <xsl:strip-space elements="*"/>

<xsl:param name="nodeNumber">2</xsl:param>


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


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


<xsl:template match="Company[ position() = 2 ]">
    <xsl:copy>
        <xsl:copy-of select="@*|node()"/>
        <Rating>Good</Rating>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

Instead of hard-coding to the second node...

<xsl:template match="Company[ position() = 2 ]">

I want to do a comparison like this so it uses a parameter value...

<xsl:template match="Company[ position() = $nodeNumber ]">

but I get an error if XSLT is 1.0...

c:\ msxsl.exe providers.xml providers.xsl

Error occurred while compiling stylesheet 'providers.xsl'.

Code:   0x80004005
Variables may not be used within this expression.

Company[ position() = -->$nodeNumber <--]

it works fine if XSLT is 2.0...

c:\ altovaxml.exe /xslt2 providers.xsl /in providers.xml

<?xml version="1.0" encoding="UTF-8"?>
<Providers>
        <Company>
                <Name>Verizon</Name>
        </Company>
        <Company>
                <Name>Sprint</Name>
                <Rating>Good</Rating>
        </Company>
        <Company>
                <Name>ATT</Name>
        </Company>
</Providers>

I need to use XSLT 1.0. Thank you very much for your time and effort...

1

1 Answers

3
votes
<xsl:template match="Company">
   <xsl:copy>
     <xsl:copy-of select="@*|node()"/>
     <xsl:if test="(count(preceding-sibling::Company) + 1) = $nodeNumber">
        <Rating>Good</Rating>
     </xsl:if>
    </xsl:copy>
</xsl:template>