XPath – Axis

Definition

Definition matters.

W3C – XPath

W3C defines Axis this way :-

Link

  1. An axis is either a forward axis or a reverse axis.
    • Forward Axis
      1. An axis that only ever contains the context node or nodes that are after the context node in document order is a forward axis.
    • Reverse Axis
      1. An axis that only ever contains the context node or nodes that are before the context node in document order is a reverse axis.
      2. Thus, the ancestor, ancestor-or-self, preceding, and preceding-sibling axes are reverse axes; all other axes are forward axes.
  2. Self Axis
    • The self axis always contains at most one node, it makes no difference whether it is a forward or reverse axis

Lab

As one plays with XPath one will get into the weeds in terms of how fully each environment supports the various XPath functions.

XML

Here is how original XML.

Image

foo.xml

XPath Query

Goal Xpath Query
Descendants
Find elements matching foo, filter on attribute id=2, get descendants //foo[@id=2]/descendant::*
Find elements matching foo, filter on attribute id=2, get first descendant node //foo[@id=2]/descendant::*[position()=1]
Find elements matching foo, filter on attribute id=2, get last descendant node //foo[@id=2]/descendant::*[last()]
Ancestor
Find elements matching foo/tar/bar, filter on attribute atrr=samuel, get ancestor //foo/tar/bar[@attr=’samuel’]/ancestor::*
Find elements matching foo/tar/bar, filter on attribute atrr=samuel, get ancestor with element matching tar //foo/tar/bar[@attr=’samuel’]/ancestor::tar
Find elements matching foo/tar/bar, filter on attribute atrr=samuel, get ancestor with element matching foo with attribute matching id is 3 //foo/tar/bar[@attr=’samuel’]/ancestor::foo[@id=3]
Find elements matching bar, filter on attribute atrr=samuel, get ancestor with element matching foo an attribute id is 3 //bar[@attr=’samuel’]/ancestor::foo[@id=3]

Tool

Here are tools you can try it out with :-

  1. XPather

XPather

Sample

XPather.XML.XQuery.Ancestor.element.foo.attribute.id.is.3

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s