Saturday, 27 June 2015

How to write xpath for SVG elements ?

Hi All

I have been working with charts, wherein I have to hover on the chart and get text from the tooltip.

In this scenario I came across SVG elements.The whole chart was present under the tag <svg> .

SVG is short for Scalable Vector Graphics. It is a graphic format in which the shapes are specified in XML. The XML is then rendered by an SVG viewer.

You can read more about SVG elements here.



 


 Sample HTML code


<svg width="400" height="110">

<g id="yui_3_6_0_1_1435305312018_1191" class="highcharts-series highcharts-tracker" visibility="visible" zIndex="0.1" transform="translate(64,37) scale(1 1)" style="cursor:pointer;" clip-path="url(#highcharts-13)">

<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">

</g>

</svg>
 
Scenario : Consider that we need to find the 2nd node of rect , present under the g tag, which is again present under the svg tag.

Our xpath would generally be something like, //svg/g/rect[2]-  but if we do that the element will not be found..


Xpath for svg elements should be like,

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


That's it for now ..


Pay it forward..

DR