We are trying to read information from a separate XML document.
This is the code we have:
'load the XMLTest document containing cars.
Dim xml As XDocument = XDocument.Load("CreditApp.xml")
Dim SSN As String = txtSSN.Text
'get all car makes that are red.
Dim query = From xe In xml.Descendants("SSN")
Where xe.Element("SSN").Value = SSN
Select New With {
.FName = xe.Element("FName").Value 'Error in code is here
}
'loop through query result output results.
For Each element In query.ToArray
MessageBox.Show(element.FName)
Next
We are getting the error:
Object reference not set to an instance of an object.
We are not sure what it is refering too.
When you seed that message it means that you tried to access a member of a variable that currently has the value of
Nothing.The value
Nothingin VB.Net (similar to C#null) means the object has no value. Attempting to access a member on it is accessing a member on nothing. The runtime can’t satisfy this request and hence throws an exception to let you know about the problem.In this particular sample it looks like the most likely cause of the error is the following line
This code doesn’t do anything to validate that
xe.Element("FName")doesn’t returnNothingand hence can lead to an exception when accessing the memberValue. To fix this you need to guard against this possibility. The easiest way is to use a helper methodWith this helper you could rewrite the original query as such