I understand that for the below xml the xpath expression "//span[position()=1]" returns the first span element anywhere in the document:


But when the same expression "//span[position()=1]" is used for the below XML, then it returns all the span elements instead of the first span element


Any help would be appreciated.

1 Answer 1


Because in your first example all your span elements reside on the same level so that they all have different positions. However in your second example each span resides within its own container (<b>) where each of them has the position=1, hence all the elements are returned.

To return first span in your second example you can use the xpath like this:

  • Thanks @Alexey for quick response. I want to focus more on this concept, can you please elaborate more on this or point to specific articles which explains this concept. Feb 20, 2019 at 10:41
  • 8@SandeshSawant It's all about the context: "The position function returns a number equal to the context position from the expression evaluation context." from developer.mozilla.org/en-US/docs/Web/XPath/Functions/position. The article gives also examples.
    – dzieciou
    Feb 20, 2019 at 14:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.