Reputation: 103
i need to check if a specific Attributes ConnectionInd
exists in the Element of FlightSegment
.
If it exist, i will store the value, if it doesnt, i will move on and read the next attributes.
The following is if it exist:
<FlightSegment ArrivalDateTime="06-16T06:10" ConnectionInd="O" DepartureDateTime="2013-06-16T00:15" SmokingAllowed="false" eTicket="true">
<Destination ... />
</FlightSegment>
And this is if it doesn't exist:
<FlightSegment ArrivalDateTime="03-27T17:35" DepartureDateTime="2013-03-27T13:30" SmokingAllowed="false" eTicket="true">
<Destination ... />
</FlightSegment>
i'm checking it with the following code but when there's no ConnectionInd
, it will throw an error saying Object reference not set to an instance of an object.
if (FlightSegment.Item(f).Attributes["ConnectionInd"].Value != "" && FlightSegment.Item(f).Attributes["ConnectionInd"] != null)
{
string conInd = FlightSegment.Item(f).Attributes["ConnectionInd"].Value;
}
Upvotes: 1
Views: 2943
Reputation: 100308
Vice versa:
First check
FlightSegment.Item(f).Attributes["ConnectionInd"] != null
then
FlightSegment.Item(f).Attributes["ConnectionInd"].Value != ""
Otherwise if it's indeed null, you will get NullReferenceException which you're actually getting.
More efficient:
var att = FlightSegment.Item(f).Attributes["ConnectionInd"];
if (var != null)
{
string cind = att.Value;
}
Upvotes: 1
Reputation: 242
There should be a method like hasAttribute or something like that that you should use instead of FlightSegment.Item(f).Attributes["ConnectionInd"].Value because if the "ConnectionInd" does not exist you are trying to get "Value" out of a null object and that will cause an exception.
Upvotes: 0