Bookmark and Share

XPath - Relative Location

Now for something completely different! XPath expressions can also be created using relative location paths. Instead of starting at the root element, you can simply reference the element you want and go from there.

Advertise on Tizag.com

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 - Relative Location Means More Options

Expressions that use relative location paths open up a whole new set of options for you. You can do things like select every amount element in an XML document.

To construct an XPath expression to select every amount element, we only need to type one word.

XPath Expression:

amount

This piece of XPath will select all of the amount elements in our lemonade2 XML document. If you were trying to find the total items in stock, this type of XPath expression would be perfect!

XPath - Relative Can Have Children Too

Just as an absolute path is often a string of children elements, a relative path can follow the same type of form. If you wanted to select every price element that had a chips parent, you would use a relative location expression like the one below:

XPath Expression:

chips/price

This expression first select all the chips elements in the document (there's just one) and then chooses the child element price.

Understanding the difference between absolute and relative position paths is the key to creating appropriate expression to select the correct XML items!

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