Constructing an XPath Location Step

MSXML 5.0 SDK

Microsoft XML Core Services (MSXML) 5.0 for Microsoft Office - XPath Developer's Guide

Constructing an XPath Location Step

A location step is constructed as follows:

axis::nodetest[predicate]

Each of the three components may or may not be present in a given expression. The expression as a whole is evaluated as a series of successively finer-grained sieves, resulting in the selection of one or more nodes from the target document:

  • The axis (separated from the node-test, if there is one, by a pair of colons, ::) establishes a "direction to look," beginning at each of the nodes selected by the node-test. There is an axis corresponding to each type of relationship defined by XPath's tree model.
  • The node-test determines the initial set of nodes to be selected.
  • The predicate is set off from the node-test and axis, if they are present, by square bracket characters, [ and ]. If a predicate is present, it defines conditions to be met in order for a given node to be ultimately selected by the XPath expression.
Note   The result of selecting by location step, even if all three components are present, does not necessarily mean that only one node will be located.

Some sample location steps using the complete syntax are shown in the following table.

Location step Description
child::*[position()=1] Locates the first child node of the context node
ancestor-or-self::book[@catdate="2000-12-31"] Locates all ancestors of any <book> child of the context node, as well as the <book> child itself, as long as the element in question has a catdate attribute with the value "2000-12-31".
//self::parent[name()="book"] | descendant::node[name()="author"] Locates any node in the document whose parent node is named "book," or any node descended from the context node whose name is "author".

Example

This example does not generate significant output. It demonstrates that no errors are generated by the above XPath expressions.

XML File (booksxpath.xml)

Use the Sample XML File for XPath Tree Model and change its href attribute to point to booksxpath.xsl.

XSLT File (booksxpath.xsl)

<?xml version='1.0'?>
<xsl:stylesheet version="1.0"
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="//book">
   <p/>child::*[position()=1] -- 
      <xsl:value-of select="child::*[position()=1]"/>
   <p/>ancestor-or-self::book[@catdate="2000-12-31"]/author -- 
      <xsl:value-of select='ancestor-or-self::book[@catdate="2000-12-31"]/author'/>
   <p/>//self::parent[name()="book"] | descendant::node[name()="author"] -- 
      <xsl:value-of select='//self::parent[name()="book"] | descendant::node[name()="author"]'/>
</xsl:template>

</xsl:stylesheet>