Calling an Extension Function

The next example shows how to make use of a function in the FunctX stylesheet library, details of which I mention later in this appendix. You can download the XSLT 2.0-compatible version of the library from

www.xsltfunctions.com/xsl/download.html.

I suggest that you choose the commented version for your download, which you should save in a convenient folder. It is advisable to retain the library intact, as there are some interdependencies.

The functx:contains-word() function works in a similar way to XPath contains(). It takes two string parameters: the first is the containing text string, and the second is the word to match. If a match is found, the function returns true. It is case-insensitive.

The word to match must be delimited by either ''non-word'' characters or the beginning or end of the first parameter. Most punctuation and whitespace characters are considered non-word characters, while letters and digits are word characters.

The function requires another function, functx:escape-for-regex(), which escapes regular expression (regex) special characters. This function is not formally declared in the calling function, as sometimes required in other languages.

Here is the code for functx:contains-word().

<xsl:function name="functx:contains-word" as="xs:boolean" xmlns:functx="http://www.functx.com" > <xsl:param name="arg" as="xs:string?"/> <xsl:param name="word" as="xs:string"/>

<xsl:sequence select=" matches(upper-case($arg), concat('"(,*\W)?', upper-case(functx:escape-for-regex($word)), M\W.*)?$'))

</xsl:function>

It uses the XPath functions matches(), concat(), and upper-case(), and calls another library function, functx:escape-for-regex(). The result is returned in an <xsl:sequence> instruction.

There is a lot of regex work going on here, and one attraction of using a library function is that you can treat it as a black box. Basically, both strings are uppercase, escaped for regex special characters, and anchored on word boundaries.

To call this function you need to ensure that the functx: namespace is declared in your stylesheet and that the functx.xsl library file is referenced in an <xsl:include> declaration. The following snippet illustrates how the function is called within an <xsl:when> test:

<?xml version="1.0" encoding="UTF-8"?>

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"

xmlns : functx="http: / /www. functx. com" exclude-result-pref ixes=" functx"

version="2.0">

<xsl:include href="functx.xsl"/>

<xsl:template match="/"> <output>

<xsl:choose>

<xsl:when test="functx:contains-word('now is the time for all good men...','bad')">

A match was found.</xsl:when> <xsl:otherwise>No match in source.</xsl:otherwise> </xsl:choose> </output> </xsl:template> </xsl:stylesheet>

0 0

Post a comment

  • Receive news updates via email from this site