mcha mcha - 1 year ago 74
HTML Question

Easy XML to HTML table

I have an XML file like the following :

<?xml version="1.0" encoding="ISO-8859-1" ?>
<mylist name="test">
<title>--$title$- not found</title>
<table>
<header>
<col name="firstname" title="--$firstname$- not found"/>
<col name="lastname" title="--$lastname$- not found"/>
<col name="country" title="--$country$- not found"/>
</header>
<body>
<row>
<col name="firstname">John</col>
<col name="lastname">Smith</col>
<col name="country">ENGLAND</col>
</row>
<row>
<col name="firstname">Peter</col>
<col name="lastname">Scott</col>
<col name="country">USA</col>
</row>
</body>
</table>
</mylist>


and I need to show the result as a HTML table like the following :

enter image description here

Could anyone help please? I'm not into XML/XSL and I just need this once

Answer Source

Try this:

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

  <xsl:template match="mylist">
    <html>
      <xsl:apply-templates />
    </html>
  </xsl:template>

  <xsl:template match="title">
    <head>
      <title><xsl:value-of select="." /></title>
    </head>
  </xsl:template>

  <xsl:template match="table">
    <table style="border: 1px solid black">
      <xsl:apply-templates />
    </table>
  </xsl:template>

  <xsl:template match="header">
    <thead>
      <tr>
        <xsl:apply-templates />
      </tr>
    </thead>
  </xsl:template>

  <xsl:template match="body">
    <tbody>
      <xsl:apply-templates />
    </tbody>
  </xsl:template>

  <xsl:template match="row">
    <tr>
      <xsl:apply-templates />
    </tr>
  </xsl:template>

  <xsl:template match="col[parent::header]">
    <th style="border: solid black 1px;"><xsl:value-of select="@name" /></th>
  </xsl:template>

  <xsl:template match="col[parent::row]">
    <td style="border: solid black 1px;"><xsl:value-of select="." /></td>
  </xsl:template>
</xsl:stylesheet>

It will actually put a style attribute on each <td> or <th> which means the output's a little verbose, but it keeps the XSLT nice & simple.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download