1

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

<div>
<span>qty</span>
<span>price</span>
<span>time</span>
</div>

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

<div>
<b><span>qty</span></b>
<b><span>price</span></b>
<b><span>time</span></b>
</div>

Any help would be appreciated.

6

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:

(//span)[1]
  • 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. – Sandesh Sawant Feb 20 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 at 14:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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