-1

This is working, but I want to use the text Group 1 as a variable.

Code trials:

[FindsBy(How = How.XPath, Using = "(.//*[normalize-space(text()) and normalize-space(.)= 'Group 1'])[1]/ancestor::app-organization//*[normalize-space(text()) and normalize-space(.)='Create a new board...']/following::input[1]")]
public IWebElement BoardNameInputField { get; set; }

I tried this but with no success:

string boardName = "Group 1";

[FindsBy(How = How.XPath, Using = "(.//*[normalize-space(text()) and normalize-space(.)='${boardName}'])[1]/ancestor::app-organization//*[normalize-space(text()) and normalize-space(.)='Create a new board...']")]
public IWebElement CreateNewBoard { get; set; }

Is it possible to do this?

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • 2
    Possible duplicate of [Using variables inside strings](https://stackoverflow.com/questions/7227413/using-variables-inside-strings) – JeffC Feb 07 '19 at 13:39

3 Answers3

5

In string interpolation the $ should be before the string, not the variable

[FindsBy(How = How.XPath, Using = $"(.//*[normalize-space(text()) and normalize-space(.)='{boardName}'])[1]/ancestor::app-organization//*[normalize-space(text()) and normalize-space(.)='Create a new board...']")]

In addition, boardName need to be static to be used outside method scope

static string boardName = "Group 1";
Guy
  • 46,488
  • 10
  • 44
  • 88
  • 1
    This is the answer to OP's question! (However: string interpolation is turned into `string.Format()` at compile-time hence my answer... :) ) – Moshe Slavin Feb 07 '19 at 13:32
  • 1
    @MosheSlavin True, but it looks like the OP tried to do it, he used `'${boardName}'`. – Guy Feb 07 '19 at 13:40
2

You can use String.Format with inserting-a-string:

string boardName = "Group 1";

[FindsBy(How = How.XPath, Using = String.Format("(.//*[normalize-space(text()) and normalize-space(.)='{0}'])[1]/ancestor::app-organization//*[normalize-space(text()) and normalize-space(.)='Create a new board...'])", boardName)]
public IWebElement CreateNewBoard { get; set; }

Hope this helps you!

Moshe Slavin
  • 5,127
  • 5
  • 23
  • 38
0

As you are setting the variable boardName to Group 1 you need to change:

How.XPath, Using = "(.//*[normalize-space(text()) and normalize-space(.)='${boardName}'])[1]/ancestor::app-organization//*[normalize-space(text()) and normalize-space(.)='Create a new board...']")]

as:

How.XPath, Using = "(.//*[normalize-space(text()) and normalize-space(.)='" + boardName + "'])[1]/ancestor::app-organization//*[normalize-space(text()) and normalize-space(.)='Create a new board...']")]

Effectively we changed:

normalize-space(.)='${boardName}'

to:

normalize-space(.)='" + boardName + "'
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352