Bookmark and Share

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.

Advertise on Tizag.com

We will be using our lemonade2.xml file, which you can download. Below is the contents of lemonade2.

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.

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