tags:

views:

40

answers:

2

I've been trying to iterate through an XML file using XSL , however I'm having major troubles as the only first language is being recognised. Help!

<?xml version="1.0"?>
<languages count="1">
  <language>English (UK)</language>
  <language>Spanish</language>
  <language>Arabic</language>
</languages>

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:template match="/">
    <html>
      <body>
        <table border="1">
            <tr>
          <xsl:for-each select="languages">
              <th>
                 <xsl:value-of select="language"/>
              </th>
          </xsl:for-each>
            </tr>
        </table>
      </body>
    </html>
  </xsl:template>
</xsl:stylesheet>
+7  A: 

You only have one languages node, at the root.

You should be using templates instead of for-each whenever possible:

<xsl:template match="language">
    <th>
       <xsl:value-of select="."/>
    </th>
</xsl:template>

And in the main template call it:

<tr>
    <xsl:apply-templates select="languages/language"/>
</tr>
Oded
@Oded: +1 for apply templates suggestion.
Alejandro
Very nice way of doing it, thanks.
wonea
+2  A: 

@Oded has probably posted the best answer atm, try to go with that. But in your specific case, you've written

<xsl:for-each select="languages">

of which there is only one, so rewrite that as

<xsl:for-each select="languages/language">

and

<xsl:value-of select="language"> 

as

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

or

<xsl:apply-templates/>

and this particular stylesheet should work for you.

So again: if you can, do what Oded suggests. Sometimes though, you will have to use a for-each-loop - if so, then hopefully my answer helps you understand what you did wrong in this case.

Rob