当前位置: 动力学知识库 > 问答 > 编程问答 >

xpath - Finding an element that has : specific attribute and a child with specific text

问题描述:

For the fallowing sample of code , i need to check if a tr ,with type="a" and that has a td with text "3" as a child ,exists:

<table>

<tr type="a">

<td>1</td>

</tr>

<tr type="b">

<td>1</td>

</tr>

<tr type="a">

<td>3</td>

</tr>

</table>

Tried this :

 b.tr( :xpath =>"//tr[@type='a']").td( :text =>'3').exists?

but it doesnt work ( the xpath expression returns only the first tr of the 2 existing).

Any ideas ?

Is there an xpath expression that will return true if the tr I need exists ?

网友答案:

Alternatively, this can also be done without xpath:

b.trs.count{ |tr|
  tr.attribute_value('type') == 'a' and tr.td(:text, '3').present? 
} > 0

A little bit more verbose, but I think it is easier to read than xpaths.

网友答案:

Use:

boolean(/*/tr[@type='a']/td[. = 3])

This XPath expression evaluates to true() exactly when there exists a td whose string value is equal to the number 3, and that has parent tr the string value of whose type attribute is "a", and which (the tr) is a child of the top element of the XML document.

Otherwise the XPath expression evaluates to false()

网友答案:
b.tr(:xpath =>"//tr[@type='a']", :index => 1).td(:text =>'3').exists?

or

b.tr(:xpath =>"(//tr[@type='a'])[2]").td(:text =>'3').exists?
网友答案:

Well am not sure if this helps but this code returns a count of how many elements the xpath expression returns , so you can check if the count is 0 then no matches otherwise it would return the number of matches :

var doc = document.evaluate("//table/tbody/tr[@type='a']/td[text()=1]",document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null);
doc.snapshotLength

or

var doc = document.evaluate("//table[@id='tableId']/tbody/tr[@type='a']/td[text()=1]",document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null);
doc.snapshotLength

if you have an id for your table.

Hope this helps in any way.

分享给朋友:
您可能感兴趣的文章:
随机阅读: