C# HtmlAgilityPack HtmlNodeCollection SelectNodes not working

1.6k views Asked by At

This is the line of code I am using, when I look in the watch window, 'c' is null.

HtmlNodeCollection c = doc.DocumentNode.SelectNodes("//*[@id=\"content\"]/table/tbody/tr[2]/td/center[2]/b");

But when I declare 'c' as this, the watch window shows it to be a valid HtmlNodeCollection

HtmlNodeCollection c = new HtmlNodeCollection(doc.DocumentNode.ParentNode);

If I then set 'c' to the first code snippet, it goes back to being null.

I know the XPath is correct, as I obtained it from the Chrome Inspect Element of the element I want to get.

1

There are 1 answers

1
Simon Mourier On

SelectNodes returns null when nothing has been found.

You think your XPATH is ok because you used a browser's (Chrome, Firefox, etc.) constructed XPATH, but unfortunately, this XPATH is not exactly the same as the one you got from the network (or a file, or a raw stream).

Browsers rely on the in-memory DOM they use internally which can be dramatically different. That's why you see elements such as TBODY that only exist in DOM, not in markup (where they are optional).

So, I suggest you get back to the string/stream you give to the Html Agility Pack and check that XPATH again. I bet there is no TBODY, for a start.