Learn about XPath Axes

Tram Ho

XPaths sometimes become inaccessible in the usual way, which requires us to cleverly combine nodes.

XPath Axes is a collection of syntaxes that support queries to relationships in Nodes. And the ultimate goal is to find the element we are looking for.

So what syntax does XPath Axes have, what is its effect. In the following article, I will share to let people understand more about XPath Axes.

1. Following

Xpath=//div[@class='mobile']//following::span allows retrieving all span tags in the source code behind a div tag with class ‘mobile’.

2. Preceding

Xpath=//div[@class='mobile']//preceding::span allows retrieving all span tags in the source code before a div tag with class ‘mobile’.

3. Descendant

Xpath=//div[@class='mobile']//descendant::span allows retrieving all span tags in source code that are descendants of a div tag with class ‘mobile’.

** The usage of Following-sibling, Preceding-sibling is similar to Descendant, when using one of these, the xpath results will return the same.

4. Ancestor

Xpath=//div[@class='mobile']//ancestor::div allows retrieving all div tags in source code as parent, ancestor of a div tag with class ‘mobile’.

5. Parent

Xpath=//div[@class='mobile']//parent::span allows retrieving all span tags that are parent tags in div tags with class ‘mobile’.

6. Child

Xpath=//div[@class='mobile']//child::span allows retrieving all span tags that are child tags in div tags with class ‘mobile’.

Refer to the full table of XPath Axes:

AxisNameDefine
ancestorSelect all ancestors (parents, grandparents, etc.) of the specified element
ancestor-or-selfSelect all ancestors (parents, grandparents, etc.) of the specified element and itself
attributeSelect all the properties of the specified element
childSelect the child of the specified element
descendantSelect all descendants and descendants of the specified element
descendant-or-selfSelect all descendants, descendants of the specified element and itself
followingSelect all elements after the specified element
following-siblingSelect all siblings after the specified element
namespaceSelect all namespaces of the specified element
parentSelect all parent elements of the specified element
precedingSelect all elements that precede the specified element
preceding-siblingSelect all siblings before the specified element
selfSelect the specified element
Share the news now

Source : Viblo