ali ali - 4 months ago 59 Question

Object reference not set to an instance of an object when using XPATH with HtmlAgilityPack

Though I have added a reference to the

from Silverlight 5, I still get this error when trying to get a link with a certain class from a HTML document:

Additional information: Object reference not set to an instance of an object.

My code:

Dim doc As HtmlDocument = New HtmlDocument()
doc.LoadHtml(New Net.WebClient().DownloadString(sourceUrl))

For Each row As HtmlNode In doc.DocumentNode.SelectNodes("//a[@class='base-link']")

If I only do
, then I don't get any error. Looks, like there's a problem when using
but I don't understand why


The exception occurs because there are no nodes selected with your XPath query.

You can guard against it with something like:

Option Infer On
' ... '
Dim myLinks = doc.DocumentNode.SelectNodes("//a[@class='base-link']")
If myLinks IsNot Nothing Then
    For Each row In myLinks
End If

I suggest that you inspect the HTML you are loading to find out what the class name is. It could be that the class name is generated by, say, JavaScript, in which case you would have to load the page into a browser control and wait for it finish processing, then get the rendered HTML and parse that.