xpath选择器中的C#变量

时间:2012-05-08 14:25:48

标签: c# xpath selenium

我可以将C#字符串变量传递给xpath选择器吗?这是用于硒单元测试。我想做这样的事情:

string myText = "foo";    
Assert.IsTrue(Browser.IsElementPresent("//option[contains(text(), $myText)]"));

4 个答案:

答案 0 :(得分:6)

使用string.Format应该可以工作:

Assert.IsTrue(Browser.IsElementPresent(string.Format("//option[contains(text(), {0}]",myText)));

答案 1 :(得分:4)

是的,您可以使用String.Format

string myText = "foo";    
Assert.IsTrue(Browser.IsElementPresent(String.Format("//option[contains(text(), {0})]", myText)));

答案 2 :(得分:0)

我看到这已经得到了解答,但您也可以这样做:

Assert.IsTrue(Browser.IsElementPresent(String.Format("//option[contains(text(), " + myText + ")]")));

这是有效的,因为C#只会将每个字符串附加到另一个字符串的末尾。

答案 3 :(得分:0)

感谢您的回答!我在桌子上做了一个Find,上面的解决方案对我不起作用,可能是因为我的字符串包含连字符,小数点和数字,如下所示:“TV-8888-ZIP-54-EN-CTR.05021031”

我将字符串分配给C#变量ID。我怀疑,由于小数点和数字,上面的答案都失败了。使用Nashibukasan的答案,我必须明确添加单引号。工作的Find语句 - 从包含第一列中的ID字符串的同一行获取表的第三列中的值 - 最终看起来像这样:

value = driver.FindElement(By.XPath(string.Format("//td[contains(text()," + "'" + ID + "'" + ")]/following-sibling::td[2]"))).Text;