ali ali - 3 months ago 43
Vb.net Question

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

Though I have added a reference to the

System.Xml.Xpath
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']")
Console.Write(row.Name)
Next


If I only do
SelectNodes("//a")
, then I don't get any error. Looks, like there's a problem when using
@class
but I don't understand why

Answer

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
        Console.WriteLine(row.Name)
    Next
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.

Comments