0

How would you convert the count of xpath to int?

int example = driver.FindElement(By.XPath("(//td[contains(@sorttable_customkey, '" + Account + "')])/preceding::a[1]")).Count;

I picked this up from question: Does anyone know why GetXpathCount() doesn't work in C#?

I can't seem to get it to work, I tried dumping the above to a list and counting the list but this also wouldn't work.

Also sort of off topic but is there a way to check if driver.FindElement(By.XPath("exp")) == null? because if it dose = null it will throw a null reference error.

1
  • "I can't seem to get it to work" is a pretty poor problem description. If you want help, you have to describe the problem. Commented Sep 23, 2013 at 22:04

2 Answers 2

1

You are looking for .FindElements.

After all, look at the method name of what you are using: FindElement. (no plural)

Therefore, the count will always be 1 ;)

Check out .FindElements, this will have a .Count property (because it's essentially a List that is returned).

As for the null checking, that is down to you but it is unneeded. The source code of Selenium shows it will never be null returned from there. It's either going to be the element you asked for, or an exception is thrown if it has trouble getting it.

So a null check would be defensive, but wasteful. Even more so since that .FindElements will just return an empty collection if it has trouble getting the element you are asking for (i.e compared to throwing an exception).

Therefore realistically speaking, you'd only get a NullReferenceException if driver was null (which would mean your entire test fails).

int numberOfElements = driver.FindElements(By.XPath("(//td[contains(@sorttable_customkey, '" + Account + "')])/preceding::a[1]")).Count;
Sign up to request clarification or add additional context in comments.

2 Comments

I thought I tried this last night and it was throwing an error, although I was coding for 12 hours straight so I could of done somthing else wrong. Anyway thanks and thank you as well Santoshsarma both are correct.
"Therefore, the count will always be 1" Even worse, there is no FindElement().Count property, because what FindElement() returns is not a collection :-)
1

You can use FindElements if you have a same locator for more than one element.

It will return ReadOnlyCollection, using that you can get count of elements:

int example = driver.FindElements(By.XPath("(//td[contains(@sorttable_customkey, '" + Account + "')])/preceding::a[1]")).Count();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.