4.3. XPath examples

Example 4.1. XPath expression examples applied on Example D.1 (page )

/cellar-book/owner                               (1)
/cellar-book/cellar/wine[quantity<2]          (2)
/cellar-book/cellar/wine[1]                      (3)
//postal-code/..                                 (4)
/cellar-book/owner/street                        (5)
//wine/@code                                     (6)
//cat:wine/@codea                                (7)
//wine[last()]/@code                             (8)
/cellar-book/cellar/wine[1]/comment/cat:bold     (9)
sum(/cellar-book/cellar/wine/quantity)           (10)
for $w in //wine return                          (11)
    concat($w/quantity,':',//cat:wine/@code[.=$w/@code]/../@name)

//cat:wine[cat:origin/cat:country='France' and cat:price<20]      (12)
                

1

The owner element of the cellar. Result : node at line 103.

2

The wines for which we have 2 bottles or less. The nodes returned are the wine elements even though the predicate uses quantity, an internal element; the predicate is evaluated in the current context of the path specified. When XPath expressions are used in the context of an XSL file, as it is most often the case, the < must be replaced by &lt; (even within strings!). Result : nodes at lines 131 and 136.

3

The first wine of the cellar. Result: node at line 120.

4

The elements which contain a postal-code element. This is achieved by finding a postal-code anywhere in the tree from the root and then getting the parent element. Result: nodes at lines 103 and 113.

5

The street of the cellar's owner. Result: 1234 rue des Châteaux

6

The value of the code attribute for all wines in the cellar. Result: C00043125, C00312363, C10263859, C00929026.

7

The value of the code attribute for all wines in the catalog (note the use of the namespace prefix). Result: C00043125, C00042101, C10263859, C00312363, C00929026.

8

The code of the last wine of the cellar. Result: C00929026.

9

The cat:bold element (note again the use of the namespace prefix) within the comment of the first wine of the cellar. Returns Guy Lapalme, Montréal(expanded from the entity &GL;)

10

Total number of bottles in the cellar by applying the predefined XPath function sum to the value of all quantity elements of the wines in the cellar. Returns 14.

11

Sequence of 4 strings each giving the number of bottles of each wine in the cellar, followed by a colon and the name of the corresponding wine: 2:Domaine de l'Île Margaux, 5:Mumm Cordon Rouge, 6:Château Montguéret, 1:Prado Rey Roble.

12

Sequence of French wines in the catalog costing less than 20 dollars: wines that start on lines 24 and 42.