Wondering
Wondering

Reputation: 5086

How to achieve this table structure using xslt

I am facing one problem while writing one xslt:

xml:

<students>
    <studentDetails tag="to" id="1" fname="AA"/>
    <studentDetails tag="mo" id="2" fname="BB"/>
</students>

writing a xslt i have to convert it into HTML:

<table>
   <tr>
      <th>to</th>
      <th>mo</th>
   </tr>
   <tr>
      <td>1</td>
      <td>2</td>
   </tr>
   <tr>
      <td>AA</td>
      <td>BB</td>
   </tr>
</table>

Now how to write this xslt?

I have tried

<xsl:template match="students">
  <table>
      <tr>
         <xsl:apply-templates select="studentDetails"/>
      </tr>
   </table>
</xsl:template>

<xsl:template match="studentDetails">
   <th>
      <xsl:call-template name="zz">
         <xsl:with-param name="child-name" select="'tag'"/>
      </xsl:call-template>
   </th>
   <td></td>
</xsl:template>

<xsl:template name="zz">
   <xsl:param name="child-name"/>
   <xsl:value-of select="@*[name() = $child-name]"/>
</xsl:template>

for its working but then my logic fails. Can somebody suggest how to code this one.

Upvotes: 0

Views: 343

Answers (2)

Andy
Andy

Reputation: 9048

This will give the output you require:

    <xsl:template match="students">
        <table>
            <tr>
                <xsl:for-each select="studentDetails">
                    <th><xsl:value-of select="@tag"/></th>
                </xsl:for-each>
            </tr>
            <tr>
                <xsl:for-each select="studentDetails">
                    <td><xsl:value-of select="@id"/></td>
                </xsl:for-each>
            </tr>
            <tr>
                <xsl:for-each select="studentDetails">
                    <td><xsl:value-of select="@fname"/></td>
                </xsl:for-each>
            </tr>                       
        </table>
    </xsl:template>

Upvotes: 3

Pete Duncanson
Pete Duncanson

Reputation: 3246

Does this not work? From what you've written this looks like what you are after?

<xsl:template match="/">
    <table>
      <tr>
        <th>to</th>
        <th>mo</th>
      </tr>
      <xsl:for-each select="/students/studentDetails">
        <tr>
          <td><xsl:value-of select="./@to" /></td>
          <td><xsl:value-of select="./@mo" /></td>
          <td><xsl:value-of select="./@fname" /></td>
        </tr>
      </xsl:for-each>
    </table>
</xsl:template>

P.S. Written off the top of my head so might not be perfect syntax...

Upvotes: 1

Related Questions