1. Computing & Technology

Answering Common Questions About XPath

Breaking down XPath – Part 2

From

XML Path Language (XPath) can be confusing, but is a crucial factor when learning XSLT. Answering some common questions that come up regarding XPath will help develop an understanding of the syntax and application of path expressions.

What is XML Path Language (XPath)?

A tool used by other languages or applications to locate data in an XML document. XPath is a snippet of code, or path expression, that finds data for selection based on established criteria.

What is XPath not?

XPath is not a standalone application. Instead, it is a form of syntax used to perform a query of XML code.

Who uses XPath?

When you see the expression "Ave." you know it to mean "Avenue." It does not matter if you see it on a map, as part of an address or listed in a sentence, it has the same meaning. This is because "Ave." is the standard accepted globally to abbreviate the word "Avenue." The same is true for path expressions. Many languages use the syntax of XPath. It is the standard format for locating and selecting data in XML. No matter who uses it, the meaning is the same. An understanding of XPath and path expressions is a prerequisite for learning XSLT. Other uses include XQuery, XLink, XPointer and JavaScript.

How do I write a path expression?

Path expressions come in many flavors. Expressions utilize nodes to form the basic syntax.

<?xml version="1.0" ?>
<catalog>
    <baseball >
        <bat lang="en" > James Smith Special</bat>
        <material> Aluminum</material>
        <price>35.00</price>
    </baseball>
</catalog>

Selecting Nodes

Path expressions use criteria to query and select nodes. Typing the node name will select all the child nodes for the named node. For example:

baseball - selects bat and material
/baseball - selects the root element of the XML document or "catalog."
//baseball/bat - will list all elements under baseball named "bat."

Predicates

A predicate is another way of writing a path expression. Predicates use bracketing to locate the node based on where it falls in the code or specific criteria.

/basesball/bat[@lang="en"] - selects all nodes under basesball that have an attribute node of lang="en"

Predicates can use operators to select nodes that fall in ranges.

/baseball/bat[price>24.00] - lists all child nodes under baseball that are over 24.00 dollars.

Axes

An axes path expression adds the family relationship into the mix. For example:

ancestor - selects all parent and grandparent nodes of the current node.

ancestor::bat - would select "baseball" and "catalog"

Writing path expressions is a complex endeavor and something that becomes clearer when studying XSLT. In fact, a basic understanding of XPath and path expressions will be the first step in mastering many of the supporting features of XML.

XPath Tutorial

©2012 About.com. All rights reserved.

A part of The New York Times Company.