Being an XML document itself, a style sheet can be manipulated by the XML DOM as easily as any other XML document. The DOM thus becomes a way to dynamically modify or parameterize a style sheet.
For example, this example uses a simple identity transformation to sort and filter stock information. The style sheet that performs the transformation looks like this:
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">
<!-- Identity transformation template -->
<xsl:template>
<xsl:copy>
<xsl:apply-templates select="@* | * | comment() | pi() | text()"/>
</xsl:copy>
</xsl:template>
<!-- Filter out stocks not listed on the nasdaq stock exchange -->
<xsl:template match="stock[@exchange != 'nasdaq']" />
<!-- Sort stocks by price -->
<xsl:template match="portfolio">
<xsl:copy>
<xsl:apply-templates select="@*"/>
<xsl:apply-templates select="stock" order-by="price"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Note This example is shown with extra white space for readability. The executable version does not contain as much white space to prevent the addition of white space into the result when transforming.
The match attribute in the second template describes which stocks should be filtered, and the order-by attribute controls how the remaining stocks are sorted. By changing these two attributes, the same style sheet can be used for a variety of transformations. The following script uses the selectSingleNode DOM method to locate these two attributes and change their values.
<SCRIPT language="JavaScript">
function sort(filter, order)
{
filterField.value = filter;
sortField.value = order;
cell2.innerText = portfolio.documentElement.transformNode(sorter.XMLDocument);
}
</SCRIPT>
<SCRIPT language="JavaScript" for="window" event="onload">
filterField = sorter.XMLDocument.selectSingleNode("//@match[0]");
sortField = sorter.XMLDocument.selectSingleNode("//@order-by");
</SCRIPT>
When the page is loaded, the second script block is executed. This block locates the desired attribute nodes and saves them for later modification. When the sort function is called, the filter and order parameters are placed in these attributes and the transformation is performed using the modified style sheet.
Sorting is initiated when the user clicks a link that calls the sort function. The various parameters used in this example are shown below.
<UL>
<LI><A href="javascript:sort('dont-match-anything', 'price')">
Sort by ascending price</A></LI>
<LI><A href="javascript:sort('dont-match-anything', '-price')">
Sort by descending price</A></LI>
<LI><A href="javascript:sort('dont-match-anything', 'symbol')">
Sort by symbol</A></LI>
<LI><A href="javascript:sort('stock[@exchange = \'nyse\']', 'symbol')">
Filter out NYSE stocks</A></LI>
<LI><A href="javascript:sort('stock[@exchange = \'nasdaq\']', 'symbol')">
Filter out NASDAQ stocks</A></LI>
</UL>
Notice that filtering is disabled by providing a pattern that will never match anything in the XML document.