XPath Expression

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

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:

		<lemonade supplier="mother" id="1">
		<pop supplier="store" id="2">

		<chips supplier="store" id="3">


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:


Let's break down this expression into easily digestible chunks:

  1. We specified the root node, inventory, at the beginning of our XPath expression.

  2. We chose inventory's child element, snack, because it is on the pathway toward our goal, "number of chips in stock".

  3. We chose snack's child element chips.

  4. 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!