XPath: Node Selection

XPath uses expressions to select a node or a set of nodes in a document tree. The most useful XPath expression is a location step. A location step can be unabbreviated or abbreviated.

An unabbreviated location step has a verbose syntax to select a node. The syntax of an unabbreviated location is:

axisname::nodetest[predicate]

where:

  • axisname specifies the type of selection that you want to perform. For example, you can use child as axisname to select child elements.
  • nodetest specifies the type of node that you want to select. The nodetest is typically the name of a node.
  • predicate contains the values that refine a search.

In the following location step, child is axisname, Messages is nodetest, and 1 is predicate. In the code snippet on the right, the location step selects the first child node, which is the first mail element under the Messages element.

  child::mail[1]

An abbreviated location step uses symbols, such as / or //, to select a node. For example, you can use / to select the root node of a document tree. In addition, you can use /Messages/mail/from expression to select the from elements in the code snippet on the right. You can also use the at sign (@) to select the attribute node of a document tree. The following location step selects the mail element in the code snippet on the right, which has an attribute named priority:

  //mail[@priority]

XPath expressions are commonly used to transform, query, and link XML data.

<Messages>
  <mail>
    <to> abc@example.com </to>
    <from> xyz@example.com </from>
    <body> Hello! How are you? </body>
  </mail>
  <mail priority="low">
    <to> another@example.com </to>
    <from> new@example.com </from>
    <body> I am not at home. </body>
  </mail>
</Messages>

Click the Next button to continue.