Sunday, 24 June 2007

Horizontally scalable HTML table

Build an horizontally scalable HTML table using XPath and XSLT


XML


<?xml version="1.0" encoding="UTF-8"?>
<ProducsList>
<Product id="1">
<SpecList>
<Spec>
<SpecLabel>Height</SpecLabel>
<SpecValue>10</SpecValue>
<SpecCat>Dimension</SpecCat>
</Spec>
<Spec>
<SpecLabel>Width</SpecLabel>
<SpecValue>6</SpecValue>
<SpecCat>Dimension</SpecCat>
</Spec>
<Spec>
<SpecLabel>Weight</SpecLabel>
<SpecValue>20.5</SpecValue>
<SpecCat>Weigth</SpecCat>
</Spec>
</SpecList>
</Product>
<Product id="2">
<SpecList>
<Spec>
<SpecLabel>Height</SpecLabel>
<SpecValue>8</SpecValue>
<SpecCat>Dimension</SpecCat>
</Spec>
<Spec>
<SpecLabel>Width</SpecLabel>
<SpecValue>5</SpecValue>
<SpecCat>Dimension</SpecCat>
</Spec>
<Spec>
<SpecLabel>Weight</SpecLabel>
<SpecValue>18</SpecValue>
<SpecCat>Weigth</SpecCat>
</Spec>
</SpecList>
</Product>
<Product id="3">
<SpecList>
<Spec>
<SpecLabel>Height</SpecLabel>
<SpecValue>5</SpecValue>
<SpecCat>Dimension</SpecCat>
</Spec>
<Spec>
<SpecLabel>Width</SpecLabel>
<SpecValue>2</SpecValue>
<SpecCat>Dimension</SpecCat>
</Spec>
<Spec>
<SpecLabel>Weight</SpecLabel>
<SpecValue>10</SpecValue>
<SpecCat>Weigth</SpecCat>
</Spec>
</SpecList>
</Product>
</ProducsList>



XSL

<xsl:template match="ProducsList">
<table>
<tr>
<th>Label</th>
<xsl:apply-templates select="Product" mode="header"/>
</tr>
<xsl:apply-templates select="
/ProducsList/Product/SpecList/Spec/SpecLabel[
not(
text()
=
ancestor::Product/preceding-sibling::Product//SpecLabel/text()
)
]
"
/>
</table>
</xsl:template>

<xsl:template match="Product" mode="header">
<th>
<xsl:text>Product </xsl:text>
<xsl:value-of select="@id"/>
</th>
</xsl:template>

<xsl:template match="SpecLabel">
<xsl:variable name="text" select="text()"/>
<tr>
<th>
<xsl:value-of select="$text"/>
</th>
<xsl:apply-templates select="/ProducsList/Product">
<xsl:with-param name="label" select="$text"/>
</xsl:apply-templates>
</tr>
</xsl:template>

<xsl:template match="Product">
<xsl:param name="label"/>
<td>
<xsl:value-of select="SpecList/Spec[SpecLabel=
$label]/SpecValue"/>
</td>
</xsl:template>



HTML

<table>
<tr>
<th>Label</th>
<th>Product 1</th>
<th>Product 2</th>
<th>Product 3</th>
</tr>
<tr>
<th>Height</th>
<td>10</td>
<td>8</td>
<td>5</td>
</tr>
<tr>
<th>Width</th>
<td>6</td>
<td>5</td>
<td>2</td>
</tr>
<tr>
<th>Weight</th>
<td>20.5</td>
<td>18</td>
<td>10</td>
</tr>
</table>

No comments: