About Me

Friday, 13 April 2012

XPath - Parent ..

XPath - Parent ..

This lesson will teach you how to select the parent of an element in your XPath expressions.

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 - Selecting a Parent with ..

Normally in an XPath expression, you have a string of elements separated by a slash. However, if you put two periods ".." where an element would normally go you can select the parent element. The element to the left of the double period will have its parent selected.
For example, if we wanted to select all of the product elements, lemonade, pop, and chips we would have to do a few expressions.

Normal XPath Expression:

inventory/drink/lemonade
inventory/drink/pop
inventory/snack/chips
However, we could instead select the parent element of amount to get the same three product elements. This is because lemonade, pop and chips all have a child amount.

Parent XPath Expression:

amount/..
This expression uses a relative path location and selects all of the amount elements in our XML document. It then uses the parent sequence ".." to select the parent element of each amount element. In our XML document, there are three amount elements, and their parents are lemonade, pop and chips!

0 comments:

Post a Comment