What Is Meant by "Axis" in XPath?

In xpath, an "axis" is way of selecting nodes relative to the current context node. It is used as a reference point to navigate through the nodes of an XML/HTML document. Each axis in xpath defines a specific direction or relationship between the nodes, allowing you to select specific sets of nodes based on their location and relationship to other nodes in the document.

There are several types of axes in xpath, each of which select a different set of nodes. However, the following four are the main axes in xpath:

  1. Child Axis — selects all child nodes of the current node;
  2. Parent Axis — selects the parent of the current node;
  3. Descendant Axis — selects all descendants (children, grandchildren, etc.) of the current node;
  4. Ancestor Axis — selects all ancestors (parent, grandparent, etc.) of the current node.

For example, consider the following XML document:

  <post category="css">
    <title>What Is CSS Pseudo-Class?</title>
    <published>2021-09-18 17:30:00</published>
  <post category="html">
    <title>What Is an HTML Entity?</title>
    <published>2021-06-26 00:00:00</published>

The following table shows examples of how you can use different axes to select a various set of nodes:

Axis Example Result
Child Axis //blog/child::post Selects all "post" nodes that are children of the "blog" node.
Parent Axis //blog/post/title/parent::* Selects the "post" parent nodes of the "title" nodes.
Descendant Axis //blog/descendant::title Selects all "title" nodes that are descendants (i.e. children, grandchildren, etc.) of the "blog" node.
Ancestor Axis //title/ancestor::blog Selects all "blog" nodes that are ancestors (i.e. parent, grandparent, etc.) of the "title" node.

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.