One of the fundamental constructs for XSL transformations and XML links, XPath is nonetheless one of the lesser lights of the XML universe. However, if you're serious about developing your XML skills, you need to know it inside out - and this tutorial has all you need to get started.
By combining the axis and node test into a location step, and combining multiple location steps into a location path, it becomes possible to locate specific nodes with the document tree quite easily. Using the following XML sample, let's consider some examples.
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="recipe.xsl"?>
<movie
id="67" genre="sci-fi">
<title>X-Men</title>
<!-- in case you didn't
know, this is based on the comic - Ed -->
<cast>Hugh Jackman, Patrick Stewart
and Ian McKellen</cast>
<director>Bryan Singer</director>
<year>2000</year>
<?play_trailer?>
</movie>
The path
/child::movie/child::cast/child::text()
references the text node
Hugh Jackman, Patrick Stewart and Ian McKellen
In order to make this a little easier to read (and write), XPath assumes a default axis of "child" if none is specified - which means that I could also write the above path as
/movie/cast/text()
Similarly, the path
/movie/comment()
references the comment string
in case you didn't know, this is based on the comic - Ed
while the path
/movie/node()[8]
references the string
Bryan Singer
The * character matches all child elements of the context node, while the @ prefix indicates that attributes, rather than elements, are to be matched. The path
/movie/*
would match all the children of the "movie" element, while the path
/movie/@*
would refer to all the attributes of the movie element. In case I need a specific attribute - say, "genre", I could use the path
/movie/@genre
or the path
/movie/attribute::genre
both of which would reference the value
sci-fi
Finally, the path
/*
would reference the first element under the document root, which also happens to be the outermost element, while the path
//*
selects all the elements in the document.
This article copyright Melonfire 2001. All rights reserved.