Select a only first matching node in XPath

You mean (note the parentheses!)

(/parent/pet/data/birthday)[1]

or, a shorter, but less specific variation:

(/*/*/*/birthday)[1]
(//birthday)[1]

or, more semantic, the "birthday of the first pet":

/parent/pet[1]/data/birthday

or, if not all pets have birthday entries, the "birthday of the first pet that for which a birthday is set":

/parent/pet[data/birthday][1]/data/birthday

If you work from a context node, you can abbreviate the expression by making it relative to that context node.

Explanation:

  • /parent/pet/data/birthday[1] selects all <birthday> nodes that are the first in their respective parents (the <data> nodes), throughout the document
  • (/parent/pet/data/birthday)[1] selects all <birthday> nodes, and of those (that's what the parentheses do, they create an intermediary node-set), it takes the first one

FYI: you can visualize the results of the various Xpath queries with the (free) XPathVisualizer tool. Works on Windows only.

alt text

Tags:

Xpath