0

The program that I have created needs to read information from a website and then store it. I am getting the error:

System.ArgumentNullException: Value cannot be null.
Parameter name: source
at System.Linq.Enumerable.Select[TSource,TResult](IEnumerable1 source, Func2 selector)

However it does not always run in error. As in sometimes it works and sometimes it doesn't work. How can this be? Here is the code that is giving me the error line 4.

IEnumerable<string> webtemp = Enumerable.Empty<string>();
if (datastring.Contains("today_nowcard-temp"))
{
    webtemp = doc.DocumentNode.SelectNodes("//div[@class = 'today_nowcard-temp']/span").Select(d => d.InnerText.Trim());

    foreach (var this_header in webtemp)
    {
        string[] temporary = this_header.Trim().Replace("Â", "-").Replace(" ", "-").Split('-');
        int f = (Convert.ToInt32(temporary[0]));
        _actualData[0].temp = GetCelsius(f);
        //Console.WriteLine(_actualData[0].temp);
    }
}
9
  • 3
    this DocumentNode.SelectNodes("//div[@class = 'today_nowcard-temp']/span") returns an null but without seeing what you have in doc it is impossible to say why that xpath doesn't return an result. Commented Aug 3, 2017 at 16:17
  • It returns a result sometimes and from what I can tell the xpath doesn't change. Commented Aug 3, 2017 at 16:18
  • We need to see the xml of your document is was @rene is getting at. Commented Aug 3, 2017 at 16:19
  • Looks like you're having a similar issues as this: stackoverflow.com/questions/38166949/… Commented Aug 3, 2017 at 16:19
  • 1
    @T.W.: Chances are that even though your xpath is not changing that the document you are downloading is. Commented Aug 3, 2017 at 16:24

1 Answer 1

3

Reason behind this exception is the value that is returned by your SelectNodes method. Sometimes it returns null and then you try to perform Linq operation on null and it generate error. So you can perform a null check on this

var temp= doc.DocumentNode.SelectNodes("//div[@class = 'today_nowcard-temp']/span");

if(temp != null){
//TODO
}
Sign up to request clarification or add additional context in comments.

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.