tags:

views:

28

answers:

3

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?

A: 

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.

Wesley Wiser
A: 

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

//contacts/names[1]
//contacts/names[2]
xil3
+1  A: 

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.

Dimitre Novatchev