About Me

Friday, 13 April 2012

XPath - Element

XPath - Element

The most common usage of XPath is for selecting elements in an XML document. This lesson will provide a walkthrough of selecting many different elements, at different levels, in the XML Tree.


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 - A Path of Elements

When trying to reach a specific element in your XML document, you often have to string together many elements to get there. In XPath you reference an element by using its name. For example, the root element's name in lemonade2.xml is inventory, so we would type the following to reference it.

XPath Expression:

inventory
If we wanted to reference the drink element of inventory, we would have to string together these two elements, starting with the root element, inventory.

XPath Expression:

inventory/drink
Notice: The elements are separated by a slash "/".

XPath - A Path of Children

If we wanted to select the price of pop, we would have to make an even longer path of elements to reach our final destination.

XPath Expression:

inventory/drink/pop/price
Notice: Each element added to this XPath expression is the child of the element before it.
  • drink is the child of inventory
  • pop is the child of drink
  • price is the child of pop
You can use this knowledge of parent-child relationships in an XPath expression to make sure your XPath is written properly.

0 comments:

Post a Comment