XPath Syntax

XPath syntax describes a path through an XML tree to reach specific nodes. Once you understand the core syntax patterns, you can build expressions that select any node or set of nodes in any XML document with precision.

Location Paths

The most important XPath expression is the location path. It describes a route from a starting point to a destination in the tree. Location paths use steps separated by slashes.

Absolute Location Path

Starts with a single forward slash — the document root.

/library/book/title

Relative Location Path

Starts from the current context node, with no leading slash.

book/title
author

Location Steps

Each step in a location path has up to three parts:

axis::nodetest[predicate]
  • axis — the direction of navigation (child, parent, ancestor, etc.)
  • nodetest — the type or name of nodes to select
  • predicate — optional filter in square brackets

Examples

child::book             → book children of current node
attribute::id           → id attribute of current node
descendant::price       → all price descendants
parent::catalog         → parent named catalog
ancestor::*             → all ancestors
following-sibling::book → book siblings after current

Abbreviated Syntax

Abbreviations make common XPath expressions shorter:

Abbreviated FormFull FormMeaning
bookchild::bookbook children
@idattribute::idid attribute
.self::node()Current node
..parent::node()Parent node
///descendant-or-self::node()/Anywhere in document
*child::*All element children
@*attribute::*All attributes

Working XML Document for Examples

<school>
  <class id="C1" grade="10">
    <student roll="S01">
      <name>Aditya Sharma</name>
      <marks subject="Math">88</marks>
      <marks subject="Science">92</marks>
    </student>
    <student roll="S02">
      <name>Bhavna Patel</name>
      <marks subject="Math">76</marks>
      <marks subject="Science">84</marks>
    </student>
  </class>
  <class id="C2" grade="11">
    <student roll="S03">
      <name>Chirag Menon</name>
      <marks subject="Math">95</marks>
      <marks subject="Science">89</marks>
    </student>
  </class>
</school>

XPath Expression Examples

Selecting Elements

ExpressionResult
/schoolThe root <school> element
/school/classBoth <class> elements
/school/class/studentAll 3 student elements
//studentAll student elements anywhere
//nameAll name elements anywhere
/school/class[1]/studentStudents in the first class only

Selecting Attributes

ExpressionResult
/school/class/@gradegrade attributes of both classes
/school/class/@*All attributes of all class elements
//student/@rollroll attributes of all students
//marks/@subjectAll subject attributes

Using Predicates

ExpressionResult
/school/class[1]First class element
/school/class[last()]Last class element
/school/class[@grade='10']Class with grade=10
//marks[@subject='Math']All marks for Math
//student[marks > 90]Students with any marks above 90
/school/class[position()=2]Same as /school/class[2]

Using Wildcards

/school/*              → All direct children of school (both class elements)
/school/class/*        → All children of all class elements (all students)
/school/class/student/*  → All children of all students (name + marks)
//*                    → Every element in the entire document
//@*                   → Every attribute in the entire document
//marks[@*]            → All marks elements that have any attribute

Multiple Selections with the Union Operator

The pipe character | combines two XPath expressions and returns nodes from both.

//name | //marks

Returns all name elements AND all marks elements.

/school/class[1] | /school/class[last()]

Returns the first and last class elements.

XPath Predicates — Advanced Patterns

//student[name='Chirag Menon']         → Student with this exact name
//marks[. > 85]                       → Marks elements with value above 85
//class[count(student) > 1]           → Classes with more than one student
//student[position() mod 2 = 1]       → Every odd-numbered student
//class[@grade and @id]               → Classes that have both attributes
//student[not(marks[@subject='Math'])] → Students with no Math marks

XPath in JavaScript

You can evaluate XPath expressions in JavaScript using the document.evaluate() method.

var result = document.evaluate(
  "//student/name",
  document,
  null,
  XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
  null
);

for (var i = 0; i < result.snapshotLength; i++) {
  console.log(result.snapshotItem(i).textContent);
}

Key Points to Remember

  • An XPath location path is a sequence of steps separated by slashes.
  • Absolute paths start with /; relative paths start from the current context node.
  • The double slash // finds matching nodes anywhere in the document.
  • @ selects attributes; * selects all elements; node() selects all node types.
  • Predicates in square brackets filter the node-set by position or condition.
  • The pipe | combines two expressions into a union — nodes from both selections.
  • Abbreviated syntax (book, @id, ., ..) makes common expressions shorter.

Leave a Comment

Your email address will not be published. Required fields are marked *