<?xml version=”1.0”?>
<inventory>
<book category=”Fiction”>
<title>Joy of Integration</title>
<author>Joe Smith</author>
</book>
<book category=”Non-Fiction”>
<title>Integration for Dummies</title>
<author>John Doe</author>
</book>
</inventory>
|
|
To the above document we need to add a reference to the XSLT template we’ll be building.
|
|
<?xml-stylesheet type="text/xsl" href="book.xsl" ?>
|
|
Note that XML documents do not need to have this statement embedded – the linking of an XML document and an XSLT template can be accomplished dynamically at runtime.
|
|
The XSLT template begins with the following header statements that simply identifies it as an XML document conforming to the W3C XSLT specification.
|
<?xml version="1.0"?>
<xsl:transform
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
|
|
The following construct establishes the base node of the XML document, to which the template applies:
|
<xsl:template match="/">
<xsl:apply-templates />
</xsl:template>
|
|
The match="/" fragment identifies the root node, which tells the XSLT processor that this template applies to the entire XML document (as opposed to a subset of the document tree).
|
|
The construct below uses XPath expressions to locate and loop through each instance of the book element. Every iteration through the loop results in the insertion of a table row consisting of category, title and author column values.
|
<xsl:template match="inventory">
<table border="1">
<xsl:for-each select="book">
<tr>
<td><xsl:value-of select="@category"/></td>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="author"/></td>
</tr>
</xsl:for-each>
</table>
</xsl:template>
|
|
The XSLT syntax is interspersed with HTML tags responsible for building the table. Note the use of the @ symbol, which identifies a value as being an attribute, as opposed to an element.
|
|
The XSLT template is completed with the following closing element:
|
|
</xsl:transform>
|
|
Here is the template in its entirety:
|
<?xml version="1.0"?>
<xsl:transform
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:template match="/">
<xsl:apply-templates />
</xsl:template>
<xsl:template match="inventory">
<table border="1">
<xsl:for-each select="book">
<tr>
<td><xsl:value-of select="@category"/></td>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="author"/></td>
</tr>
</xsl:for-each>
</table>
</xsl:template>
</xsl:transform>
|
|
Upon opening the XML document, the sample template will generate HTML formatted output that a browser should render as follows:
|
| Fiction | Joy of Integration | Joe Smith |
| Non-Fiction | Integration for Dummies | John Doe |
|