This chapter is from the book

This chapter is from the book

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.

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.

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.

TIPS

This test can be used in xsl:template and xsl:apply-templates processing, as well as condition testing using xsl:if and xsl:when.

If you just want to test that a node set exists (regardless of its contents), skip Steps 2–3.

String and text values in Step 3 should be enclosed in single quotes.

Use the and operator to test that all of a series of multiple conditions are true. Use the or operator to test if at least one of a series of multiple conditions is true. Other boolean operators are not valid.

There is also a boolean expression not, but it is a function, it is not an operator. For more details, see More XPath Functions on page 59.