ana
ana

Reputation: 485

Create table from node XML, XSLT

I'm getting data from an XML-file and transforming it with XSLT. I have one node that I want to create a table from.

<?xml version="1.0" encoding="utf-8"?>

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

<xsl:variable name="file" select="document('file.xml')"/>

<xsl:template match="/">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
    </head>
    <body>
        <table>
           <xsl:value-of select="$file/Workbook/Worksheet/Table"/>
        </table>
    </body>
</html>

//output: id firstname lastname 8 Jonas Berg 15 Adam Jones ...

I want the table to look like:

id    firstname    lastname
8     Jonas        Berg  
...

Can I do that?

XML sample from table:

 <Row>
<Cell ss:Index="2"><Data ss:Type="String">id</Data></Cell>
<Cell ss:StyleID="s62"><Data ss:Type="String">firstname</Data></Cell>
<Cell><Data ss:Type="String">lastname</Data></Cell>
 </Row>
   <Row>
    <Cell ss:Index="2"><Data ss:Type="Number">8</Data></Cell>
    <Cell ss:StyleID="s62"><Data ss:Type="String">Jonas</Data></Cell>
    <Cell><Data ss:Type="String">Berg</Data></Cell>
   </Row>

Upvotes: 0

Views: 570

Answers (1)

Tomalak
Tomalak

Reputation: 338316

This is very simple. The only challange is to get the XML namespaces right.

<xsl:stylesheet 
  version="1.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
  xmlns="http://www.w3.org/1999/xhtml"
>
  <xsl:output 
    type="xml"
    doctype-public="-//W3C//DTD XHTML 1.0 Strict//EN"
    doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
  />

  <xml:strip-space elements="*" />

  <xsl:template match="/">
    <head>
      <title></title>
    </head>
    <body>
      <table>
        <xsl:apply-templates />
      </table>
    </body>
  </xsl:template>

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

  <xsl:template match="Cell">
    <td><xsl:apply-templates /></td>
  </xsl:template>

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

</xsl:stylesheet>

Notes

  • The XHTML namespace must be declared as the default namespace in your XSLT, otherwise the result document won't be XHTML.
  • Excel's spreadsheet namespace must be declared - I used the same prefix that Excel uses - ss.
  • The doctype-public and doctype-system attributes create the correct doctype declaration for XHTML.
  • The rest is a matter of translating <Row> to <tr> and <Cell> to <td>, which is easy with two simple templates.
  • You could write additional, more specialized templates like <xsl:template match="Data[@ss:Type='Number']"> that output certain data types with a different format.

Upvotes: 1

Related Questions