-2

When using the HtmlAgilityPack my code is erroring out the minute it hits a snag before i can implement any type of check, for example:

                Dim doc = New HtmlDocument()
                doc.LoadHtml(sl)
                Dim searchId = doc.DocumentNode.SelectSingleNode("//input[@name='searchId']").Attributes("value").Value

When it hit's this line (after working fine)

                Dim searchId = doc.DocumentNode.SelectSingleNode("//input[@name='searchId']").Attributes("value").Value

I get the object not set to a reference, i know it's because it doesn't see this value in the html code, i'm not sure the best way to check it isn't empty so i can continue the execution otherwise the application crashes.

Can anyone help?

Dan Puzey
  • 33,626
  • 4
  • 73
  • 96
graham23s
  • 385
  • 3
  • 14
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Ňɏssa Pøngjǣrdenlarp Jul 12 '15 at 13:56

1 Answers1

0

Your failing line consists of several property lookups, separated here for clarity::

Dim searchId = doc
                .DocumentNode
                .SelectSingleNode("//input[@name='searchId']")
                .Attributes("value")
                .Value

If any one of these lookups (except for .Value) is null, you will get the error you describe. For example, if there's no matching @name='searchId' element, the .Attributes call will throw the error.

In order to prevent the error, you need to check each result separately before trying the next lookup. doc.DocumentNode is unlikely to be Nothing (assuming that your document is valid and loaded correctly), so something like this:

Dim searchId As String
If doc.DocumentNode.SelectSingleNode("//input[@name='searchId']") IsNot Nothing Then
    If doc.DocumentNode.SelectSingleNode("//input[@name='searchId']").Attributes("value") IsNot Nothing Then
        searchId = singleNode.Attributes("value").Value
    End If
End If

You can shorten the code and prevent the nested If by using the short-circuiting AndAlso operator. I'd also add a temporary variable for readability:

Dim searchId As String
Dim idNode = doc.DocumentNode.SelectSingleNode("//input[@name='searchId']")

If idNode IsNot Nothing AndAlso idNode.Attributes("value") IsNot Nothing Then
    searchId = idNode.Attributes("value").Value
End If
Dan Puzey
  • 33,626
  • 4
  • 73
  • 96