Pitt-Greensburg Digital Studies Logo: I Code!

Maintained by: Elisa E. Beshero-Bondar (ebb8 at pitt.edu) Creative Commons License
Last modified:

What is XPath and How Does It Work?

Remember how we’ve described XML as like “nested boxes” or a “tree”? (Review that, if you like, on our page explaining XML “So What Exactly is XML anyway?”) Think of a whole XML file as a big box, and nested inside it are smaller boxes. If we think of XML as a tree, we can consider the whole file as springing from one root, and branching out in complex ways.

XPath is a language that we write to select parts (or nodes) of an XML document, so we can pick out the pieces, remix them, add to them, count them, number them, etc. We write what’s called an XPath expression so a computer can follow the path we lay out to to certain parts of an XML document. The way we express this needs to be very precise, though often there are multiple ways of creating a path or identifying a location in a document.

Though we sometimes “do XPath” for its own sake while we’re coding our files, to help us find particular things, or check or count something, most often we use XPath expressions within XML-transformation languages, including XQuery (XML Query Language) and XSLT (eXtensible Stylesheet Language Transformations). XPath is a “helper” or ancillary language that’s necessary to work with these transformation languages, which allow us to remix, rewrite, extract pieces from, and add pieces to XML files. Before you can write these transformations, you need to learn XPath.

XML is Made of Nodes

Think of our nested boxes in XML as made of nodes. A node is a position on the XML tree, and can be one of three things:

  1. an element (or the element node), which, remember, contains the start and end tags and everything inside: from <element> . . .contents . .</element> .
  2. an attribute (or the attribute node, which contains attributes and their values inside tags, as in @item="beads" in the element <trade item="beads">.
    (Note, we’ll use the @ symbol to indicate an attribute value from now on.)
  3. plain text (or the text node), which is only the text content within an element. (We locate the text node in cases when we want to strip out elements and preserve only the text.)

This link provides a handy picture of how element nodes and text nodes fit together in a "tree:" David Birnbaum’s XPath intro page on nodes.

We’ve shown you the Outline View in <oXygen/>, and it may be helpful to look at an outline of a file now, to explain how nodes relate to each other.

outline view in oXygen

Element and text nodes are described in XPath like a big family of ancestors, descendents, parents, children, and siblings.

In the Outline view of this HTML file which we took from <oXygen/>, we’ve marked multiple levels of a family relationship: The yellow highlighted root node <html> is the original ancestor of all the descendents inside. The red circled nodes (the <head> and <body> elements) are the immediate children of the <html> root node. They are also siblings to each other.

What’s the relationship of the <div> node to the <html> root node? It’s a grandchild, or a descendant. And it’s the child of the <body> element. See how that works?

The elements I’ve circled in green may help us to visualize siblings, all the children of <div>. In XPath, we can distinguish these siblings in relation to each other. The second element circled in green, the <p> element with the text “Remember how we’ve described...”, is the "following-sibling" to the <b> element holding the text "Fall 2013 Digital Humanities." And we can say that the preceding-sibling to the <ol> element is the <p> element, which holds the text, “Think of our nested boxes in XML...”

Axes in XPath

What we’ve just been describing about family relationships is closely connected to axes in XPath. XPath’s default is to locate the child of the current context node (or the current position designated in the XML file). Basically, when you designate an axis in an XPath expression, you’re indicating the direction you want your path expression to go: Do you want it to look up to a parent or ancestor? Or down to a child or descendent?

ancestor:: The ancestor axis sends you to parents and above, all the way up to the root node.
parent:: or . . The parent axis sends you up a short distance, to the immediate parent of the context node.
child:: or / The child axis (which is the default) sends you down to the immediate child of the context node.
descendant:: or // The descendent axis sends you down to the children and their children, and their children’s children, etc.
preceding-sibling:: The preceding-sibling axis sends you to the “left” to the siblings that come before the context node (the big brothers and sisters, or earliest children of a parent).
following-sibling:: The following-sibling axis sends you to the “right” to the siblings that come after the context node (the little brothers and sisters, or younger children of a parent.
self:: or . There’s actually a “self” axis designating the current context node.
attribute:: or @ One last axis that’s sort of in its own parallel universe: the attribute (@) axis! You can follow one of the paths up or down or left or right among elements, and if you want to locate attributes in particular, or want to locate only the elements with a particular attribute or attribute value, you move to the @ axis.

When we write path expressions, we indicate the axis, and we could indicate the name of an element we’re searching for, or another node specifier like the text node or text(). There’s a longhand form for specifying axes, and sometimes that longhand comes up in the XPath window in <oXygen/>, so it can be handy to know what these are and what they mean. Use whatever form of these makes the most sense to you as you’re writing your XPath expressions.

How to Write an XPath Expression

So you want to start writing an XPath expression already! Here we go. Use the XPath 2.0 window in the upper left of your <oXygen/> screen. An XPath expression is a kind of journey, and it begins by figuring out where you are (what’s your context node?) and taking a step along an axis direction.

When we start writing XPath expressions, we usually begin from the root or “document node” at the top of the tree, and many of our path expressions will begin with a double slash: //, which is shorthand for the descendant axis: If we *start* our XPath expression with the double slash, we indicate we’re beginning at the top-level document node and working our way down:


This expression means, start at the beginning node of the document and look for the body element anywhere below. Next, switch to the child axis, and take one step to find the immediate children of body--the div elements (however many there are). Then find all p elements that are the immediate children of all the div elements.

What if we want to return all the elements at a particular level, regardless of what they are? Here’s where we use the asterisk: *. Examples:



Notice how these work: We say, in the first one, start from the document (root) node, and go down to find the body element, then all the div elements that are children of body, and then please return all the elements that are the immediate children of div. How’s the second one different from the first? Notice that we take a longer step down with that double slash: This says, with all those div elements that are children of body, please look down the descendent axis and return all the elements that are either the children or the descendents of div.

With the last two, notice we designate the axis first. The parent::* will return the name of the parent element for the current context node, whatever it is. (“Who’s my mommy?“) The last one I wrote for the sake of writing it: What if we were somehow lost in an XML file and just wanted to return the name and location of the current context node: (“Where am I??” or “Who am I?”)

Now, a single slash, /, typically indicates taking a step in a path expression, and when it’s used by itself, it means, “take one step down and find the immediate children of the context node.” When we’re writing XQuery and XSLT we’ll find ourselves writing XPath expressions from specific points inside a document (not necessarily from the root or document node up at the top), so in those cases we might actually begin an expression like this:


This means, starting from the current context node, look for the immediate children named p, and then go down and find all the immediate children of p named span.

So how do we work with attributes? They have their own @ axis. Here are some examples of how you can access the attribute axis and what you might find:



The parents are attributes are technically elements, so very frequently we climb down (or up) an axis to locate a parent element, and then shift over to the attribute axis with the /@, as we did in the second example here. Notice with the first example, though, that this actually starts from the document (root) node, and hunts through the whole document looking for all instances of the @id inside elements wherever it may turn up. If you download this html file that you’re reading, open it in <oXygen/> and run that XPath, click on the results in the bottom view window, and they’ll highlight just the attribute portions of their elements.

Predicates, the Filters of XPath: [ ]

Predicates in XPath are filtering tools. When we write these, we want to keep in mind the structure of the document, and the direction that the computer processor “looks” as it’s following your XPath expression. David Birnbaum gives a good flowchart explanation of how this works on the “Predicates” section of his XPath site. When you write a predicate, you indicate how to select a specific thing out of a lineup, a particular paragraph based on its position, for example. You write a predicate using square brackets:



So, say we have multiple div elements, each of which has multiple p children. The first expression returns, for each div in turn, its first p child. In my document, I have two divs with p children, so this XPath returns 2 results, the first paragraph only in each of these divs.

The second is a little more complex: Can you work it out? Here we use predicates in two steps of our XPath expression, to streamline results at each level: First, we say, look for ONLY the div element with the @id="space". We filter out all of the other divs which have different @id attribute values, then, and we ONLY look inside this one div that has this distinguishing characteristic. Then, we step down and find its first p child. Make sense?

Now, you can actually set multiple predicates [][] right next to each other in an XPath expression. Here’s an example of when you might need to do this: Say you have a file divided up into multiple sections using div elements. Let’s say that several of these div elements are designated with @type, as in <div type="poem"> to indicate a particular kind of content inside. You may have other div elements designated as @type="preface" and @type="acknowledgments". So this file is basically a “book” of poems with some accompanying material, and the div elements separate each poem from the others. Now, let’s say you want to find your way with XPath to the fifth poem in the file. Here’s how you’d do that by making two predicates side by side:


See how this works? First you say, find me the div elements filtered by @type="poem", and then filter those results to give me just the fifth one in the sequence.

Functions, How to Do Things with XPath: ( )

Functions let us do some processing of the things we locate with XPath expressions. What if you don’t want to return all the p elements inside a div, and you just want to count them all? That’s when we use a function called count(). You put in parentheses the nodes you want to count, and this can work in lots of ways:





In the first of these, I’ve written an expression that says, "Count the number of times the @id attribute is used in this file, starting from the root (document) node. (When I run it here in <oXygen/> as I’m writing this document, the answer is 3 (as I see in the bottom window).

The second expression, //div/count(p), says, start from the root node, go down to ALL the div elements in the file, and then count the p elements in EACH div, one by one. My bottom view screen in <oXygen/> gives me a set of three results, with a count for each div in turn. That can be handy!

But what if we want to find out how many p elements there are total under ALL the divs? That’s what the third expression, count(//div/p) does: It gives just ONE result, and it’s a count of ALL the p elements in ALL the divs, without differentiating them div by div by div. Let’s think about why this gives a different result from the previous example: This has everything to do with where you place the count function! When you place the count at the end, and don’t include the div element in the parentheses, you effectively step down the tree to each div, and THEN do a count of the p elements inside each. By contrast, when you say count(//div/p), the computer postpones the counting until it’s found all the p’s everywhere that are children of divs. The count function says, “Hey! round up ALL the p’s that are children of divs, and count those.”

Can you figure out what the last expression is counting? //div[@id="space"]/count(p)

This combines a predicate with a function! So you indicate that you want to start with only one div, the one with the @id="space" . Then you count the number of p elements in that div.

Using Functions and Predicates Together: Some Complex XPath!

You can actually put functions inside predicates in XPath as a way to filter your results! Here’s an example: Say we want to find any and all div elements that have just one p child? We’d write that expression this way:

//div[count(p) = 1]

Here’s another example. What if want to return an div element that doesn’t have ANY p elements? Here we’d use a predicate again, and this time use a function called not()


About these examples: Notice that when you put a function in an XPath predicate, you don’t have to indicate that you’re stepping down a tree to get the child element. The default expectation when we don’t give an axis is that we’re stepping down to the immediate child.

Quite often in writing XPath, we’re trying to find something in terms of its position. We’ve given you examples of predicates that return a specific numerical position, as in the first or fifth paragraph or div element, using [1] or [5]. But what if you don’t have an exact position, but know you want to return, say, the first 10 of a particular element? Here’s where we can use the position() function.

//div[@type="poem"][position() < 10]

This retrieves the first 10 <div type="poem"> elements in an XML collection of poems chunked in divs. The predicate expressions work to filter by grabbing all the appropriate “poem” divs whose position is 10 or under. Note that nothing goes inside the parentheses for position(). Context functions like this keep the parentheses open. (Basically, position() and last() are written differently from the mathematical functions like count(), where we indicate a particular thing to be counted inside the parentheses.)

Here’s another useful positional function: last()

As you might expect, last() returns the last of a thing you’ve designated. This is another positional function frequently used in predicates. So, where //p[1] returns the first <p> element in the document, //p[last()] returns the last, wherever it is, and it’s handy because we usually don’t know how many p elements (or paragraphs) there are in a big file! Again, note that nothing goes inside the parentheses for this positional function.

XPath has a little over 100 different functions to choose from, but in most project scenarios, you really only need to work with a handful, which you’ll get to know pretty well. (One of our favorites is distinct-values(), which we’ll show you. We use distinct-values to eliminate repetition in a list of results, so we get only the distinctly different things, like the names of elements we’ve used, for example. Don’t try to memorize these, but you’ll need to look them up periodically and find one to use. Here are some useful XPath function lists, with explanations of what the functions do and how they work:

Finally, here’s a link to a handy quick review of terms and symbols, thanks to David Birnbaum! Check out his combination of predicates and functions in the expression with string-length() just above the review: See if you can follow it.