Thursday, October 29, 2009

Finding the position of an element

To find the position of element <b>col_d</b> in the following xml:
1
2
3
4
5
6
7
<a>
<b>col_a</b>
<b>col_b</b>
<b>col_c</b>
<b>col_d</b>
<b>col_e</b>
</a>

U can probably use the following xpath:

count(//b[normalize-space(text())="col_d"]/preceding-sibling::b)+1

But it doesn't work for me in nokogiri, so what i did was:
1
2
doc = Nokogiri::XML(above_xml_string)
doc.xpath('//b[normalize-space(text())="col_d"]/preceding-sibling::b').count + 1

That's all !!

No comments:

Post a Comment

Labels