Sagar
Sagar

Reputation: 49

XSLT transformation for an xml that has nodes with the same name

I have an XML in this format,

<?xml version="1.0" encoding="ISO-8859-1"?>
<catalog>
<cd>
    <title>Empire Burlesque</title>
    <title>Hide your heart</title>
    <title>Greatest Hits</title>
    <title>Still got the blues</title>
    <title>Eros</title>
    <title>One night only</title>
</cd>
</catalog>

The XSLT for this XML is,

<?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>
        <table border="1">
          <tr>
            <th>Title</th>
          </tr>
          <xsl:for-each select="catalog/cd/title">
          <tr>
            <td><xsl:value-of select="title"/></td>
          </tr>
          </xsl:for-each>
        </table>
      </body>
    </html>
</xsl:template>
</xsl:stylesheet>

I want the output to look like,

Title

Empire Burlesque
Hide your heart
Greatest Hits
Still got the blues
Eros
One night only

When i try to transform the above XML, i am getting an empty table, but with no titles in it. Please help me with this so i can get the expected output as shown above. Thanks in advance.

Upvotes: 3

Views: 92

Answers (1)

hielsnoppe
hielsnoppe

Reputation: 2869

There is just a minor flaw in your solution. See my comment in the following code:

<?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>
        <table border="1">
          <tr>
            <th>Title</th>
          </tr>
          <xsl:for-each select="catalog/cd/title">
          <tr>
            <!-- you have to reference '.' instead of 'title' because this is the
              current context node since you iterate over 'title' elements with
              for-each -->
            <td><xsl:value-of select="."/></td>
          </tr>
          </xsl:for-each>
        </table>
      </body>
    </html>
</xsl:template>
</xsl:stylesheet>

Upvotes: 4

Related Questions