About Me

Friday, 13 April 2012

XPath - Descendants "//"

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.


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.

0 comments:

Post a Comment