Menu

Bug with position()?

Help
2002-01-22
2012-10-08
  • Sven Axelsson

    Sven Axelsson - 2002-01-22

    Is this a bug or is it just me?

    Using Instant Saxon 6.5
    this input:
    <root>
        <item>1</item>
        <item>2</item>
        <item>3</item>
    </root>

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

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

    <xsl:template match="item">
      <p>Node: <xsl:value-of select="."/>,
         Position: <xsl:value-of select="position()"/>,
         Last: <xsl:value-of select="last()"/></p>
    </xsl:template>
    </xsl:stylesheet>

    Gives this output:
    <html>
       <body>
          <p>Node: 1,
             Position: 2,
             Last: 7
          </p>
          <p>Node: 2,
             Position: 4,
             Last: 7
          </p>
          <p>Node: 3,
             Position: 6,
             Last: 7
          </p>
       </body>
    </html>

    That's not what I expected. But I'm still a newbie in the XML business, it might be my understanding that's lacking.

     
    • Michael Kay

      Michael Kay - 2002-01-22

      It's not a bug, and it's not just you: it's a common misunderstanding.

      Your <xsl:apply-templates/> call is processing all the child nodes of the <root> element. There are seven of them: three item elements and four whitespace text nodes. The item elements (at positions 2, 4, and 6) are processed by your template rule. The text nodes (at positions 1, 3, 5, and 7) are processed by the built in rule for text nodes, which copies the (invisible) content to the result tree.

      The solution is either to specify <xsl:apply-templates select="*"/> to process element children only, or to remove the whitespace text nodes using <xsl:strip-space elements="*"/>.

      Mike Kay

       
      • Sven Axelsson

        Sven Axelsson - 2002-01-22

        Ah, so that's why.

        I tried my code with MSXML first and that one does not behave in this manner. As is documented in your book, I believe. I think I have some more reading to do.