1
votes

My xml looks like this

<catalog>
<cd>
 <title>Empire Burlesque</title>
 <artist>Bob Dylan</artist>
 <country>USA</country>
 <company>Columbia</company>
 <price>10.90</price>
 <year>1985</year>
</cd>
<cd>
 <title>Hide your heart</title>
 <artist>Bonnie Tyler</artist>
 <country>UK</country>
 <company>CBS Records</company>
 <price>9.90</price>
 <year>1988</year>
</cd>
</catalog>

what I want to achieve is the html table where number of rows are dynamic, for example:

table should look like this:

TABLE HEADER
<tr>
 <td>Title</td>
 <td>Empire Burlesque</td>
</tr>
<tr>
 <td>Artist</td>
 <td>Bob Dylan</td>
</tr>
<tr>
 <td>country</td>
 <td>USA</td>
</tr>

Goes on For all the nodes available for cd.

All I want to be able to loop for number of nodes available under <cd> and generate individual <tr> for each node in the html output. So that I dont have to use <xsl:value-of select> with particular xml node name.

Can anyone help me understand the basic of the part? Thanks.

1

1 Answers

0
votes
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="catalog">
    <table>
      <xsl:apply-templates select="cd/*"/>
    </table>
  </xsl:template>

  <xsl:template match="cd/*">
    <tr>
      <td>
        <xsl:value-of select="name()"/>
      </td>
      <td>
        <xsl:value-of select="."/>
      </td>
    </tr>
  </xsl:template>

</xsl:stylesheet>

Output:

<table>
  <tr>
    <td>title</td>
    <td>Empire Burlesque</td>
  </tr>
  <tr>
    <td>artist</td>
    <td>Bob Dylan</td>
  </tr>
  <tr>
    <td>country</td>
    <td>USA</td>
  </tr>
  <tr>
    <td>company</td>
    <td>Columbia</td>
  </tr>
  <tr>
    <td>price</td>
    <td>10.90</td>
  </tr>
  <tr>
    <td>year</td>
    <td>1985</td>
  </tr>
  <tr>
    <td>title</td>
    <td>Hide your heart</td>
  </tr>
  <tr>
    <td>artist</td>
    <td>Bonnie Tyler</td>
  </tr>
  <tr>
    <td>country</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>company</td>
    <td>CBS Records</td>
  </tr>
  <tr>
    <td>price</td>
    <td>9.90</td>
  </tr>
  <tr>
    <td>year</td>
    <td>1988</td>
  </tr>
</table>