MMP
MMP

Reputation: 39

XML Transformation to HTML using XSLT

I have simple xml as below

<Scores>
    <Score1>
       <Name>A</Name>
       <Address>Address1</Address>
    </Score1>

    <Score2>
       <Name>B</Name>
       <Address>Address2</Address>
    </Score2>
</Scores>

I want it's output in HTML table as below. (HTML table will have 2 columns headers "Name" and "Address", and i need it's values in rows) I do not want to hardcode "Name" and "Address" headers. They may change in future.

Name            Address
A               Address1
B               Address2

Can you please let me know what will be the XSLT for this?

Upvotes: 2

Views: 1240

Answers (1)

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56162

Use:

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

    <xsl:template match="/Scores">
        <table>
            <tr>
                <xsl:for-each select="*[1]/*">
                    <th>
                        <xsl:value-of select="local-name()"/>
                    </th>
                </xsl:for-each>
            </tr>
            <xsl:apply-templates select="*"/>
        </table>
    </xsl:template>

    <xsl:template match="*">
        <tr>
            <xsl:for-each select="*">
                <td>
                    <xsl:value-of select="."/>
                </td>
            </xsl:for-each>
        </tr>
    </xsl:template>

</xsl:stylesheet>

Output:

<table>
  <tr>
    <th>Name</th>
    <th>Address</th>
  </tr>
  <tr>
    <td>A</td>
    <td>Address1</td>
  </tr>
  <tr>
    <td>B</td>
    <td>Address2</td>
  </tr>
</table>

Upvotes: 1

Related Questions