XSLT: Foreach iterates over each element but displays the value of the first element?

I have a list of items and for each item I want to make it a 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?

+1


a source to share


2 answers


What you do with the expression value is select all the tag nodes in the xml document:

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

      

The effect of this 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 list for each.

+4


a source


More XSLT way to do the right thing is to add a tag template and change the 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>

      

+5


a source







All Articles