Gandalf StormCrow
Gandalf StormCrow

Reputation: 26202

How to get nodes using xpath

When I have 2 set of nodes with same element name for ex :

<contacts>
    <names>
      ...
    </names>
    <names>
      ...
    </names>
</contacts>

Normally I'd use //contacts/names to get the node, but how do I do if they have the same name how do I get second or first or nth?

Upvotes: 1

Views: 326

Answers (3)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243449

For the provided XML document use:

/contacts/names[1]

the above selects the first names element.

/contacts/names[2]

the above selects the second names element.

Try to avoid using the // abbreviation as much as possible, because it is usually grossly inefficient, causes all the (sub)tree roted in the context node to be traversed.

Upvotes: 1

xil3
xil3

Reputation: 16439

You can do this to get the first and/or second specifically:

//contacts/names[1]
//contacts/names[2]

Upvotes: 0

Wesley Wiser
Wesley Wiser

Reputation: 9851

Use //contacts/names[n] to get the nth names node. For example: //contacts/names[1] gets the first names node while //contacts/names[2] gets the second names node, etc.

Upvotes: 0

Related Questions