开发者

xslt nested for-each with comma separated list

I have xml file with list of hobby as :

<?xml version="1.0" encoding="utf-8"?>
<users>
  <user>
    <fname>somename</fname>
    <hobbies>
      <hobby>Movie</hobby>
      <hobby>Trekking</hobby>
    </hobbies>
  </user>
</users>

Xsl file:

<?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="/">
    <html>
      <body>
        <xsl:for-each select="users/user">
          <h2>
            &l开发者_运维问答t;xsl:value-of select="fname" />
          </h2>
          <h3>Hobbies :</h3>
          <xsl:for-each select="hobbies">
            <xsl:value-of select="." />
                <xsl:if test="position() != last()">
                    <xsl:text> , </xsl:text>
                </xsl:if>
          </xsl:for-each>
        </xsl:for-each>
      </body>
    </html>
  </xsl:template>
</xsl:stylesheet>

Here i used

            <xsl:if test="position() != last()">
                <xsl:text> , </xsl:text>
            </xsl:if>

to generate commas in between the list of hobbies

But the values are displayed without comma.

I am testing this on http://www.w3schools.com/xsl/'s tryit editor.

Whats wrong here? What should i do?


You have a typo, I think: <xsl:for-each select="hobbies/hobby">

Update:

Correct XSLT:

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
        <html>
            <body>
                <xsl:for-each select="users/user">
                    <h2>
                        <xsl:value-of select="fname" />
                    </h2>
                    <h3>Hobbies :</h3>
                    <xsl:for-each select="hobbies/hobby">
                        <xsl:value-of select="." />
                        <xsl:if test="position() != last()">
                            <xsl:text> , </xsl:text>
                        </xsl:if>
                    </xsl:for-each>
                </xsl:for-each>
            </body>
        </html>
    </xsl:template>
</xsl:stylesheet>

Output:

<html>
  <body>
    <h2>somename</h2>
    <h3>Hobbies :</h3>Movie , Trekking</body>
</html>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜