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.

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 everyamount 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!