XPath Functions
In the last two chapters, you learned how to use XPath location paths to specify nodes and node sets in an XML source document.
In some cases, I used location paths for further processing by templates (xsl:template and xsl:apply-templates), or in test conditions (xsl:if and xsl:when). In both of these cases, there are times that you will not need or want to use all the data in the node set returned. With XPath functions, you can apply additional logic to these node sets to return only the data you need.
In other cases, I used location paths to extract the contents of a node using xsl:value-of. Remember, xsl:value-of outputs the string value of the first node in a node set. With XPath functions, you can perform one or more operations on that string before it is output to modify the final result.
In this chapter, I will detail many common XPath functions. The official specifications for XPath Version 1.0 functions can be found at the World Wide Web Consortium site: www.w3.org/TR/xpath#corelib.
As noted, even though the most current version of the XPath language is 2.0, this and the previous chapter detail XPath Version 1.0. This is because version 1.0 is still the more widely used and widely supported version. XPath 2.0 is discussed in detail in Chapter 15. As well, specifications for the new version can be found at: www.w3.org/TR/xpath20/.
Comparing Two Values
Perhaps the most common test that you can perform on a location path is whether one value is bigger than another (Figure 4.1). You can then use this answer to determine which actions should result, or simply use the resulting node set in your transformation.
x s l t ... <h2>Overview</h2> <table border="1"><tr><th>Wonder Name</th><th>Location</th> <th>Height</th></tr> <xsl:apply-templates select="ancient_wonders/ wonder[height > 100]"> <xsl:sort select="height" order="descending" data-type="number" /> </xsl:apply-templates> </table> ...
Figure 4.1 In this example, I am using a comparison to refine the node set being used in the xsl:apply-templates instruction. Specifically, it is saying that only those wonder nodes that have a height greater than 100 will be used.
Figure 4.2 Based on the XSLT in Figure 4.2 above, four of the seven wonders have a height greater than 100 as shown above. Notice that, in addition to the Overview section of the output, I applied the same height condition to the History section, too.
To compare two values:
- Create the path to the first node set that you want to compare.
- Then, type = (equal to), != (not equal to), > (greater than), >= (greater than or equal to), < (less than), or <= (less than or equal to), depending on how you want to compare the two values.
- Finally, type a value or a path to the node set that you want to compare with the first node set identified in Step 1.