ChatGPT解决这个技术问题 Extra ChatGPT

Get Nth child of a node using xpath

My sample input XML is:

<root>
 <a>
   <b>item</b>
   <b>item1</b>
   <b>item2</b>
   <b>item3</b>
   <b>item4</b>
 </a>
</root>

I am suppose to select a node b whose position is the value of a variable.

How can I use the value of a variable to test the position of a node?


r
remi bourgarel

you can use this:

/root/a/b[position()=$variable]

position() is 1 based

http://saxon.sourceforge.net/saxon6.5.3/expressions.html


Remember it's not 0-indexed. I just spent 2 hours wasting my time looking for something at position 0.
R
Ronald Wildenberg

The following should work:

/root/a/b[2]

And if it doesn't, try:

/root/a/b[position()=2]

I came here to find the difference between these two, could you please explain how they are different?
position() refers to the position in the dom [2] refers to the second result in the list of results.
@Andre. When used inside a for-each loop select statement, they are the same. When position() is used within the loop itself, it refers to the result set. The [n] format only works as a shorthand because it is the only conditional inside the [ ] block, otherwise position() must be used, as in //a[(@id="xx") and (position()=3)], which is "any fifth link that has an id of xx".
@Patanjali That is confusing - links with the position() of 3 are the 5th links? It seems to me [2] could be used instead of :nth-of-type(2), while [position()=2] would be the equivalent of :nth-child(2) then? I guess we need a couple of examples to clear the fog.
@Patanjali I think I understood the part about it being a shorthand now that I've tested it and it does only give me the "item1" by running \\*[2] and \\*[position()=2] against the question's XML. Thank you!