Bookmark and Share

XPath - Descendants "//"

As you know, the slash "/" is used to separate parent from child in our XPath expressions. However, when you put two slashes together "//", it does something completely different. Two slashes are used to select the descendants of an element.

Advertise on Tizag.com

This lesson will teach you how to advance your XPath knowledge and save time with the descendant double-slash "//".

We will be using our lemonade2.xml file, which you can download.

XML Code, lemonade2.xml:

<inventory>
	<drink>
		<lemonade supplier="mother" id="1">
			<price>$2.50</price>
			<amount>20</amount>
		</lemonade>
		<pop supplier="store" id="2">
			<price>$1.50</price>
			<amount>10</amount>
		</pop>
	</drink>

	<snack>
		<chips supplier="store" id="3">
			<price>$4.50</price>
			<amount>60</amount>
			<calories>180</calories>
		</chips>
	</snack>

</inventory>

XPath - Choosing Descendants

Although relative and absolute paths will let you select anything you want in your XML document, they can sometimes be quite time-consuming. If you wanted to select each price element that was a descendant of drink, you would have to write two absolute XPath expressions.

Absolute XPath Expression:

inventory/drink/lemonade/price
inventory/drink/pop/price

Or you could use the relative XPath expressions.

Relative XPath Expression:

drink/lemonade/price
drink/pop/price

Although this isn't that much work, imagine if you had fifty different types of drinks, each with their own price. Not only that, but you would have to write additional XPath expressions as more drinks were added and taken away from the XML document!

The "//" sequence will save you a lot of time. If you wanted to select every price element that has a drink ancestor, this expression would get the job done.

Relative Location with Descendants XPath Expression:

drink//price

This powerful little expression has a lot going on, so let's look at it in more detail to ensure you understand how it works.

  1. We start our expression with the relative location drink.
  2. We tell XPath that we want to select from the descendants of drink with "//"
  3. We specify that we specifically want to select the price descendant.
  4. We pat ourselves on the back for getting the job done efficiently!

With the use of the descendant sequence "//", you can save yourself a lot of time. The hard part of XPath is the sheer number of solutions for a given problem, but with some practice, you'll be able to choose which set of tricks will get the job done in the best way.

Bookmark and Share




Download Tizag.com's XML Book

If you would rather download the PDF of this tutorial, check out our XML eBook from the Tizag.com store.

Found Something Wrong in this Lesson?

Report a Bug or Comment on This Lesson - Your input is what keeps Tizag improving with time!

Advertise Here

More Tutorials!
Microsoft Office Tutorials Artist Tutorials