Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XSLT value() and position() give incorrect indices

Tags:

xml

xslt

Can someone please explain me why I get the following output applying the follwoing xsl-file to the xml-file.

<?xml version="1.0" encoding="ISO-8859-1"?>
<source>    
    <number>1</number> 
    <number>2</number> 
    <number>3</number> 
    <number>4</number> 
    <number>5</number> 
    <number>6</number> 
    <number>7</number> 
    <number>8</number> 
</source>

====================================

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version = '1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
<xsl:template match="number">
   <p>
   <xsl:value-of select="position()"/>
   <xsl:text> of </xsl:text>
   <xsl:value-of select="last()"/>
   </p>
</xsl:template>
</xsl:stylesheet>

======================================

<p>2 of 17</p> 
    <p>4 of 17</p> 
    <p>6 of 17</p> 
    <p>8 of 17</p> 
    <p>10 of 17</p> 
    <p>12 of 17</p> 
    <p>14 of 17</p> 
    <p>16 of 17</p> 

I don't quite get why the output is not 1 of 8, 2 of 8 and so on.

like image 844
user1765902 Avatar asked Jan 06 '14 13:01

user1765902


People also ask

How do you reassign a variable value in XSLT?

You cannot - 'variables' in XSLT are actually more like constants in other languages, they cannot change value. Save this answer.

What is number () in XSLT?

Specifies the format pattern. Here are some of the characters used in the formatting pattern: 0 (Digit)

Which symbol is used to get the element value in XSLT?

The <xsl:value-of> element is used to extract the value of a selected node.

What is the correct syntax of for each in XSLT?

The <xsl:for-each> element selects a set of nodes and processes each of them in the same way. It is often used to iterate through a set of nodes or to change the current node. If one or more <xsl:sort> elements appear as the children of this element, sorting occurs before processing.


1 Answers

Try adding strip-space as shown below:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version = '1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
  <xsl:strip-space elements="*"/>
  <xsl:template match="number">
   <p>
   <xsl:value-of select="position()"/>
   <xsl:text> of </xsl:text>
     <xsl:value-of select="last()"/>
   </p>
</xsl:template>
</xsl:stylesheet>

This gives the following output:

<p>1 of 8</p>
<p>2 of 8</p>
<p>3 of 8</p>
<p>4 of 8</p>
<p>5 of 8</p>
<p>6 of 8</p>
<p>7 of 8</p>
<p>8 of 8</p>

This is due to whitespace issues, as described in this document. Basically the nodeset contains whitespace nodes that are not matched by your template, but contribute to the index of each node.

like image 64
ColinE Avatar answered Oct 13 '22 01:10

ColinE