0
votes

I just started working with selenium c#. I am having a treeview and its position is inconsistent so i want to expand it if it is not expanded and if it is already expanded it should be as it is. similar for the collapse.

this is when the tree is expanded

<div class="rtTop">
     <span class="rtSp"></span>
     <span class="rtMinus"></span>
     <span class="rtIn">Roles</span>
</div>

and this is when it is collapse

<div class="rtTop">
     <span class="rtSp"></span>
     <span class="rtPlus"></span>
     <span class="rtIn">Roles</span>
</div>

and I am currently using

public static string treeviewExpand( string treeviewExpandButton)
{
    treeviewExpandButton = "//span[text()='" + treeviewExpandButton + "']/preceding-sibling::span[@class='rtPlus']";
    return treeviewExpandButton;
}
public static string treeviewCollapse(string treeviewCollapseButton)
{
    treeviewCollapseButton = "//span[text()='" + treeviewCollapseButton + "']/preceding-sibling::span[@class='rtMinus']";
    return treeviewCollapseButton;
}

the above xpath works fine if the appropriate action is called. but I want a generic action function for expand and collapse of tree irrespective of its current state.

I tried to get current class name of the treeview node by using the text. here i am trying to get the current class "rtPlus" or "rtMinus" but when I try to get the preceding sibling using tag name as span I am getting the tag span with class "rtsp" and not with the class "rtPlus" or "rtMinus" even though the inspect shows its preceding sibling span has class "rtPlus"or "rtMinus"

I am using

public static string treeviewExpandCollapse(string treetext)
{
    treetext= "//span[text()='" + treetext+ "']";
    IWebElement element;
    element = driver.FindElement(treetext).FindElement(By.XPath("./preceding-sibling::span"));
    string calsss = element.GetAttribute("class");

    Thread.Sleep(2000);
}
1

1 Answers

1
votes

XPaths can be tricky, especially if you begin chaining multiple FindElement and XPaths together. For your scenario, I would keep it simple by utilizing only one XPath:

"//span[text()='" + text + "']/parent::div/span[2]"

Explanation:

  • //span[text()='" + text + "'] - select the <span> with the given text
    • <span class="rtIn">Roles</span>
  • /parent::div - select the <span>'s parent
    • <div class="rtTop">
  • /span[2] - within the parent, select the <span> at index 2 (regardless of if the <span> is expanded or collapsed)
    • <span class="rtPlus"></span>

Code:

IWebElement element = driver.FindElement(
    By.XPath("//span[text()='" + text + "']/parent::div/span[2]"));