2

I have this following xml fragment.

<root>
  <site type="main">
    <link>http://stackexchange.com</link>
  </site>
  <site type="qa">
    <link>http://stackoverflow.com</link>
  </site>
  <site type="qa">
    <link>http://superuser.com</link>
  </site>
  <site type="">
    <link>http://data.stackexchange.com</link>
  </site>
</root>

I want to select the first site's link of type "qa". I think //site[@type="qa"][1] should do it. But id does not work.

Genghis Khan
  • 970
  • 2
  • 11
  • 21

1 Answers1

4

Give a try to (//site[@type="qa"])[1]/link/text().

Or, alternatively:

//site[@type="qa"][position()=1]/link/text()

Tested on http://www.xpathtester.com/, results into http://stackoverflow.com.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • Why `//site[@type="qa" and position() = 1]/link/text()` would not work? – Genghis Khan Jul 08 '13 at 08:04
  • You are asking for both conditions to be true simultaneously. You should first search for `qa` attribute and then check the position: `//site[@type="qa"][position()=1]/link/text()`. See also this [answer](http://stackoverflow.com/a/1006439/771848). – alecxe Jul 08 '13 at 08:13