XPath Child Axis Tutorial 🎯

beginner
18 min

XPath Child Axis Tutorial 🎯

Welcome to the XPath Child Axis tutorial! In this lesson, we'll explore one of the most fundamental concepts of XPath - the Child Axis. By the end of this tutorial, you'll be able to traverse and select elements within an XML document using the Child Axis.

What is the Child Axis? 📝

The Child Axis in XPath helps you to select elements that are direct children of another element. It's a way to navigate through an XML document, focusing on the relationship between parent and child nodes.

Getting Started 💡

Let's start with a simple XML example:

xml
<bookstore> <book id="bk101"> <author>Gambardella, Matthew</author> <title>XML Developer's Guide</title> <genre>Computer</genre> <price>44.95</price> <publish_date>2000-10-01</publish_date> </book> <book id="bk102"> <author>Ralls, Kim</author> <title>Midnight Rain</title> <genre>Fantasy</genre> <price>5.95</price> <publish_date>2000-12-16</publish_date> </book> </bookstore>

The Child Axis Syntax 💡

The Child Axis syntax is simple: element-name/. To select all direct child elements of a specific parent, use the parent element name followed by the / symbol and the child element name.

For instance, to select the title elements within the book elements, we would use:

//book/title

Practical Example 💡

Let's find all book titles that belong to the "Computer" genre:

  1. First, locate the genre elements with the value "Computer".
//genre[. = 'Computer']
  1. Next, select the direct child elements of these genre elements, which are the book elements.
//genre[. = 'Computer']/..
  1. Now, find the title elements within these book elements.
//genre[. = 'Computer']/../title
Quick Quiz
Question 1 of 1

What does the Child Axis in XPath help you to do?

Quiz Time 🎯

  1. Which XPath expression selects all author elements within the book elements? A: //book//author B: //book/author C: //author Correct: B Explanation: //book/author selects all direct child author elements within the book elements.

  2. Given the following XML snippet:

xml
<store> <category name="electronics"> <product id="prod1"> <name>TV</name> <price>600.55</price> </product> <category name="clothing"> <product id="prod2"> <name>T-Shirt</name> <price>25.99</price> </product> </category> </category> </store>

Which XPath expression selects all product names within the "clothing" category? A: //category/name = 'clothing'/product/name B: //category[name = 'clothing']/product/name C: //name[. = 'T-Shirt'] Correct: B Explanation: //category[name = 'clothing']/product/name selects all direct child name elements within the product elements, which are located within the "clothing" category.