XSLT 2.0 and XPath 2.0 Programmer's Reference, 4th Edition (190 page)

BOOK: XSLT 2.0 and XPath 2.0 Programmer's Reference, 4th Edition
6.61Mb size Format: txt, pdf, ePub

Using a Simple Key

The detailed rules for keys seem complicated, but most practical applications of keys are very simple. Consider the following key definition:


This defines a key whose name is
product-code
, and which can be used to find

elements given the value of their
code
attribute. If a product has no
code
attribute, it won't be possible to find it using this key.

To find the product with code value
ABC-456
, you can write, for example:


Note that you could just as well choose to index the attribute nodes:


To find the relevant product you would then write:


I've used

here as an example. This will select all the

elements in the current document that have code
ABC-456
(I never said it had to be a unique identifier) and apply the matching template to each one in turn, processing them in document order, as usual. I could equally have used any other instruction that uses an XPath expression; for example, I could have assigned the node set to a variable, or used it in an

element.

The second argument to the key function should normally be a value of the same type as the
use
expression in the

declaration. It won't usually be a literal, as in my example, but is more likely to be a value obtained from somewhere else in the source document, or perhaps supplied as a parameter to the stylesheet. It may well have been passed as one of the parameters in the URL used to select this stylesheet in the first place; for example, a Web page might display a list of available products such as the one in
Figure 6-7
.

Clicking the Buy Now! button might cause a URL such as the following to be sent to the server:

http://www.naxos-breakfasts.com/servlet/buy?product=“TK0372&quantity=“1”

You then write a servlet (or an ASP.NET page if you prefer) on your Web server that extracts the query parameters
code
and
quantity
and fires off your favorite XSLT processor specifying
products.xml
as the source document,
show-product.xsl
as the stylesheet, and
TK0372
and
1
as the values to be supplied for the global stylesheet parameter called
prod-code
and
quantity
. Your stylesheet might then look like the one that follows.





   

   

   

   

      

There is no product with this code


   

   

   

   


Other books

The Arrangement by Mary Balogh
Tiona (a sequel to "Vaz") by Laurence Dahners
Pearl by Mary Gordon
Build My Gallows High by Geoffrey Homes
Helluva Luxe by Essary, Natalie
A Night With the Bride by Kate McKinley
Bear by Ellen Miles