Entry
How can I parametrize the order-by attribute in an xsl stylesheet?
Dec 19th, 2000 11:14
Martin Honnen,
An xsl stylesheet is an xml document itself which you can navigate with
dom and xpath methods and then change attribute values.
Here is an example for IE5+ which loads two xml documents, one being
the data, the other the xsl to transform the data to a html table for
output in the browser. When both documents are loaded, the xsl is
applied to the xml to produce a table. This table itself contains
clickable headers to change the sorting of the table.
The function which does the sorting simply selects the appropriate node
in the stylesheet and changes its order-by attribute.
Here is the html:
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JScript">
var xml = new ActiveXObject('Microsoft.XMLDOM');
xml.async = false;
xml.load('test10122000.xml');
var xsl = new ActiveXObject('Microsoft.XMLDOM');
xsl.async = false;
xsl.load('test10122000.xsl');
function changeOrder (property) {
var forEach = xsl.selectSingleNode('//xsl:for-each[@order-by]');
var orderBy = forEach.getAttribute('order-by');
if (orderBy.indexOf(property) == -1)
orderBy = '+ ' + property;
else if (orderBy.charAt(0) == '+')
orderBy = '- ' + property;
else
orderBy = '+ ' + property;
forEach.setAttribute('order-by', orderBy);
target.innerHTML = xml.transformNode(xsl);
}
</SCRIPT>
</HEAD>
<BODY ONLOAD="if (window.changeOrder) changeOrder('power');">
<DIV ID="target"></DIV>
</BODY>
</HTML>
Here is the xml data:
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="test10122000.xsl"?>
<gods>
<god>
<name>Kibo</name>
<home>http://www.kibo.com</home>
<power>42</power>
</god>
<god>
<name>Allah</name>
<home>http://www.allah.org</home>
<power>0</power>
</god>
<god>
<name>Jehovah</name>
<home>http://www.vatican.va</home>
<power>0</power>
</god>
</gods>
Here is the xsl stylesheet:
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">
<xsl:template match="/">
<TABLE BORDER="1">
<TR>
<xsl:for-each select="gods/god[0]/*">
<TH ONCLICK="changeOrder(this.innerText)"
STYLE="cursor: hand;"
>
<xsl:eval>this.nodeName</xsl:eval>
</TH>
</xsl:for-each>
</TR>
<xsl:for-each select="gods/god" order-by="- name">
<TR>
<xsl:for-each select="*">
<TD>
<xsl:value-of/>
</TD>
</xsl:for-each>
</TR>
</xsl:for-each>
</TABLE>
</xsl:template>
</xsl:stylesheet>