XPath child element

In XPath, the “child” axis is used to select the immediate XPath child element of a context node. It allows you to navigate through the hierarchical structure of an XML document or an HTML page.

The syntax for selecting the child elements in XPath is as follows:

/parentElement/childElement

Or if you want to get all children of the context node, you can use the:

/parentElement/childElement/child::elementname

Here, “parentElement” represents the parent node, and “childElement” represents the child node you want to select.

For example, let’s say we have the following XML structure:

<books>
  <book>
    <title>Harry Potter</title>
    <author>J.K. Rowling</author>
  </book>
  <book>
    <title>The Lord of the Rings</title>
    <author>J.R.R. Tolkien</author>
  </book>
</books>

If you want to select all the “book” elements that are direct children of the “books” element, you would use the XPath expression:

/books/book

This expression will return a node set containing both “book” elements.

Select First Child Element

Now if want to get only the first child of the context node. The /books/book path will return all the child elements with the name book from the same hierarchy. To return the first child of books, we will use the predicate here:

/books/book[1]

Select an element based on the child’s child value

Now suppose we have a scenario where we want to select an element based on the child element value. In this case, we will use the predicate here also but in a different way.

/books/book[title eq 'Book 1']

This XPath will select the book element where the child element ‘title’ of the book has the value ‘Book 1’.

Selects a child element anywhere in the document

If we want to find or select a child element of the context node but don’t know the XPath of that child element. We will use (//) with the child element as per below:

books//book

The above XPath will find the book element anywhere in the document and return the all child book element, no matter where there are.