Friday, May 6, 2011

XSLT: Foreach iterates for each item, but displays the value of the first item?

Hi,

I have a item list and for each item I want to make it an url.

List:

 <root>
   <tags>
     <tag>open source</tag>
     <tag>open</tag>
     <tag>advertisement</tag>
     <tag>ad</tag>
   </tags>
 </root>

XSLT:

<xsl:template match="*">
    <div class="tags">
      <xsl:for-each select="/post/tags/tag">
          <a href="#">
            <xsl:value-of select="//tag"/>
          </a>
      </xsl:for-each>
    </div>
</xsl:template>

Output:

  <div class="tags"> 
    <a href="#">open source</a> 
    <a href="#">open source</a> 
    <a href="#">open source</a> 
    <a href="#">open source</a> 
  </div>

What am I doing wrong?

From stackoverflow
  • What you are doing with the value-of expression is selecting all of the tag nodes in the xml document:

    <xsl:value-of select="//tag"/>
    

    The effect of that is that only the first selected node will be used for the value.

    You can use the following instead:

    <xsl:value-of select="."/>
    

    Where select="." will select the current node from the for-each.

    pre63 : Thank you! I tried at first and it did nothing...
    Oded : Thanks for letting me know - removed the incorrect usage.
  • A more XSLT way of doing the correct thing is add a "tag" template and modify your original:

    <xsl:template match="*">
        <div class="tags">
            <xsl:apply-templates select="tag" />
        </div>
    </xsl:template>
    
    <xsl:template match="tag">
          <a href="#">
            <xsl:value-of select="."/>
          </a>
    </xsl:template>
    

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.