XPath - Expressions
XPath can locate any type of information in an XML document with one line of code. These one liners are referred to as "expressions," and every piece of XPath that you write will be an expression. Just to make it crystal clear, here's the definition of an expression as it relates to our usage.
- expression: In programming, a line of source code that returns a value when executed. ~Computer Desktop Encyclopedia
An XPath expression is exactly that; it's a line of code that we use to get information from our XML document.
XPath - Our Sample XML File
We have slightly modified our lemonade XML document to make it more interesting. Our new XML document is lemonade2.xml, and it has had a couple new attributes and elements added to it, which we have highlighted.
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 Simple XPath Expression
An XPath expression describes the location of an element or attribute in our XML document. By starting at the root element, we can select any element in the document by carefully creating a chain of children elements. Each element is separated by a slash "/".
For example, if we wanted to know the number of chips we have in stock(element amount) in lemonade2.xml, the XPath expression would be:
XPath Expression:
inventory/snack/chips/amount
Let's break down this expression into easily digestible chunks:
- We specified the root node, inventory, at the beginning of our XPath expression.
- We chose inventory's child element, snack, because it is on the pathway toward our goal, "number of chips in stock".
- We chose snack's child element chips.
- Finally, we chose chips' child element amount, or in other words, "number of chips in stock".
If it helps to think of this XPath expression graphically, this is the pathway we followed from the root node inventory down to our desired element, amount.
XPath Trace:
XPath - Getting Started
Now that you've got your feet wet, it is time to learn the different types of XPath expressions and how to select those desired XML elements with XPath!
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! |