Can I pass a C# string variable into an xpath selector? This is for a selenium unit test. I want to do something like this:
string myText = "foo";
Assert.IsTrue(Browser.IsElementPresent("//option[contains(text(), $myText)]"));
使用string.Format应该可以工作:
Assert.IsTrue(Browser.IsElementPresent(string.Format("//option[contains(text(), {0}]",myText)));
yes you can use String.Format
string myText = "foo";
Assert.IsTrue(Browser.IsElementPresent(String.Format("//option[contains(text(), {0})]", myText)));
I see this has already been answered but you could also just do:
Assert.IsTrue(Browser.IsElementPresent(String.Format("//option[contains(text(), " + myText + ")]")));
This works because C# will just append each string to the end of the other.
Thank you for your answers! I was doing a Find in a table, and the above solutions did not work for me, possibly because my string contained hyphens, a decimal point, and numerals like so: "TV-8888-ZIP-54-EN-CTR.05021031"
I assigned the string to the C# variable ID. The answers above failed, I suspect, due to the decimal point and numerals. Using Nashibukasan's answer, I had to explicitly add single quotes. The working Find statement--that gets the value in the third column of the table from the same row that contains the ID string in the first column--ended up looking like this:
value = driver.FindElement(By.XPath(string.Format("//td[contains(text()," + "'" + ID + "'" + ")]/following-sibling::td[2]"))).Text;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.