The question recently came up about possible ways to filter data in a browser client where the source was an XML file. There are, of course, many different ways this could be done, but I decided to use XSL to create a list of the data in XHTML and to include JavaScript in the XSL file which will actually handle the filtering. It is a very simple example but I thought someone might find it useful.
searchxml.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet href="searchxml.xsl" type="text/xsl" ?>
<jobs>
<job>
<name>Shoe Sales</name>
<desc>Selling shoes</desc>
<coast>East</coast>
</job>
<job>
<name>Food Taster</name>
<desc>Taste food</desc>
<coast>East</coast>
</job>
<job>
<name>Computer Programmer</name>
<desc>Program computers</desc>
<coast>West</coast>
</job>
<job>
<name>Teacher</name>
<desc>Teach students</desc>
<coast>East</coast>
</job>
<job>
<name>Kite Flyer</name>
<desc>Fly kites</desc>
<coast>West</coast>
</job>
</jobs>
searchxml.xsl
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" omit-xml-declaration="yes" indent="yes" />
<xsl:template match="/">
<xsl:apply-templates />
</xsl:template>
<xsl:template match="jobs">
<html>
<head>
<title>Search Jobs</title>
<script type="text/javascript">
//<![CDATA[
function doSearch() {
var rb = document.getElementsByName("whichCoast");
var v;
for (var i = 0; i < rb.length; i++) {
if (rb[i].checked) {
v = rb[i].value;
break;
}
}
var jobs = document.getElementsByTagName("li");
for (var j = 0; j < jobs.length; j++) {
if (jobs[j].className == "job") {
var li = jobs[j].getElementsByTagName("li");
for (var k = 0; k < li.length; k++) {
if (li[k].className == "coast") {
if (v == "Either" || li[k].firstChild.nodeValue.match(v)) {
jobs[j].style.display = "";
} else {
jobs[j].style.display = "none";
}
}
}
}
}
}
//]]>
</script>
</head>
<body>
<form action="#" onclick="doSearch();" onsubmit="return(false);">
<label>East <input type="radio" name="whichCoast" value="East"/></label>
<label>West <input type="radio" name="whichCoast" value="West"/></label>
<label>Either <input type="radio" name="whichCoast" value="Either" checked="checked"/></label>
</form>
<ul>
<xsl:for-each select="job">
<li class="job">
<ul>
<li class="name"><xsl:value-of select="name"/></li>
<li class="desc"><xsl:value-of select="desc"/></li>
<li class="coast"><xsl:value-of select="coast"/></li>
</ul>
</li>
</xsl:for-each>
</ul>
</body>
</html>
</xsl:template>
</xsl:stylesheet>



Post a Comment