Showing posts with label xpath. Show all posts
Showing posts with label xpath. Show all posts

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

Wednesday, October 28, 2009

Getting the nearest xpath ancestor

Given the following xml fragment:
1
2
3
4
5
<a>
<a>
<b/>
</a>
<a>

To find the nearest ancestor <a/> w.r.t <b/>, i use:

//b/ancestor::a[1]

That's all !!

Sunday, October 25, 2009

Workaround for Webrat's have_xpath()

I have the following xpath:

//td[normalize-space(text())='Peter']/parent::tr//label[normalize-space(text())="Present"]/@for

It is valid, yet webrat's have_xpath() kept complaining that it cannot find it. As a workaround, i did something like this in my cucumber:
1
2
hdoc = Nokogiri::HTML(response.body)
(field_id = hdoc.xpath(the_above_rejected_xpath)).first.should_not be_nil

That's all.

2 Way to Fetch a Node's Attribute Value

There are at least 2 ways to fetch a node's attribute value using xpath:

# Method 1

//a/b/@c

# Method 2

//a/b/attribute::c

Labels