1

I am writing xpath for elements present under svg tag. I want to get the 2nd rect node.

My xpath finds all 3 nodes, whereas my requirement is to find only the 2nd -

xpath: //*[name()='svg']/*[name()='rect' and @fill='#919EF9']

HTML sample,

<svg width="400" height="110">
<rect id="yui_3_6_0_1_1435305312018_1190" x="35.5" y="60.5" width="68" height="117" stroke="#FFFFFF" stroke-width="1" fill="#919EF9" rx="0" ry="0">
<rect x="176.5" y="65.5" width="68" height="48" stroke="#FFFFFF" stroke-width="1" fill="#919EF9" rx="0" ry="0">
<rect x="316.5" y="30.5" width="68" height="70" stroke="#FFFFFF" stroke-width="1" fill="#919EF9" rx="0" ry="0">
</svg>
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
dev
  • 123
  • 3
  • 4
  • 10

2 Answers2

4

Use [n] to select the nth element:

//*[name()='svg']/*[name()='rect' and @fill='#919EF9'][2]
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
1

use following XPATH

//svg/rect[2]
h4k3r
  • 91
  • 5
  • It is missing the `@fill='#919EF9'`, but otherwise, why wouldn't it work for SVG? – Jim L. Jun 27 '15 at 19:51
  • 2
    This works, //*[name()='svg']/*[name()='rect'] , the usual way of writing xpaths don't. See http://stackoverflow.com/questions/14592213/selenium-webdriver-clicking-on-elements-within-an-svg-using-xpath – dev Jun 28 '15 at 04:17