8 - Searching for text with the contains() function

XSLT script: iliad08.xsl
<xsl:stylesheet version = '1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
<xsl:template match="/">

<table border="1" cellpadding="5">
<th>Line #</th> <th>Line</th>

<xsl:for-each select="document/poem/line">
	<xsl:if test="contains(., 'Achilles') = 'true'">
		<td> <xsl:value-of select="@num" /> </td>
		<td> <xsl:value-of select="." /> </td>

<td colspan="2">
<b> Total hits: <xsl:value-of select="count(document/poem/line[contains(.,'Achilles') = 'true'])" /> </b>

Syntax: contains(string1, string2)

Returns "true" if the first string contains the second one; returns "false" if it does not.

In this example we want the script to search each line to find out which ones contain the word "Achilles". To do this we use the xsl:for-each command to look at every line, then xsl:if combined with the contains() function to test whether or not that line (string1) contains the word "Achilles" (string2). If the contains() function returns "true" then the XSL script is told to display that line's number and contents in an HTML table. The "." in the syntax contains(.,'Achilles') represent the current node (just as ".." represent one node up the XPath tree).

Finaly, we use the contains() function again within a count() function to tally the number of lines in which "Achilles" appears.

RESULTS of iliad08.xsl
Line # Line
1 Sing, oh goddess, about the wrath of Achilles son of Peleus,
7 the son of Atreus, ruler of men, and god-like Achilles.
Total Hits: 2
Each line in which "Achilles" appears is displayed along with the line number. The total number of lines in which "Achilles" appears is tallied and displayed.