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.
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.
Let's start with a simple XML example:
<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 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
Let's find all book titles that belong to the "Computer" genre:
genre elements with the value "Computer".//genre[. = 'Computer']
genre elements, which are the book elements.//genre[. = 'Computer']/..
title elements within these book elements.//genre[. = 'Computer']/../title
What does the Child Axis in XPath help you to do?
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.
Given the following XML snippet:
<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.