XML

Number Functions

The XPath number functions should be somewhat familiar to you since you saw them in action back in Tutorial 13 when you created XSLT stylesheets that relied on the number functions. Following are the most commonly used number functions in XPath:

  • ceiling() Round up a decimal value to the nearest integer

  • floor() Round down a decimal value to the nearest integer

  • round() Round a decimal value to the nearest integer

  • sum() Add a set of numeric values

Following is an example of how to use the sum() function to add up a bunch of attribute values:

sum(cart/item/@price)

Of course, you can make nested calls to the XPath number functions. For example, you can round the result of the sum() function by using the round() function, like this:

round(sum(cart/item/@price))

The Role of XPath

You may have noticed that I've used the word "select" a lot in this tutorial when explaining how an XPath expression effectively selects part of a document. However, this selection process doesn't take place within XPath alone. XPath is always used in the context of another technology such as XSLT, XPointer, or XLink. The examples of XPath that you've seen in this lesson must therefore be used in conjunction with additional code. For example, the following code shows how one of the training log expressions from earlier in the tutorial might be used in an XSLT stylesheet:

<xsl:value-of select="*/session[@type='running']" />

In this code, the XPath expression appears within the select attribute of the xsl:value-of element, which is responsible for inserting content from a source XML document into an output document during the transformation of the source document. Refer back to Tutorials 12 and 13 for more information on XSLT stylesheets and how they are used. The point I want to make here is that the XSLT xsl:value-of element is what makes the XPath expression useful. XPath plays a critical role in XSLT, as you probably remember from Tutorial 13.

Similar to its role in XSLT, XPath serves as the addressing mechanism in XPointer. XPointer is used to address parts of XML documents, and is used heavily in XLink, which you learn about in a moment. XPointer uses XPath to provide a means of navigating the tree of nodes that comprise an XML document. Sounds familiar, right? XPointer takes XPath a step further by defining a syntax for fragment identifiers, which are in turn used to specify parts of documents. In doing so, XPointer provides a high degree of control over the addressing of XML documents. When coupled with XLink, the control afforded by XPointer makes it possible to create interesting links between documents that simply aren't possible in HMTL, at least in theory.