Walter Fabio Simoni
Walter Fabio Simoni

Reputation: 5729

Don't have a nullReferenceException on XML Parsing

I have wrote a c# function in order to parse an XML Stream. My XML can have several nodes.

Example :

<Stream>
 <One>nnn</One>
 <Two>iii</Two>
 <Three>jjj</Three>
</Stream>

But sometimes, it is :

<Stream>
 <Two>iii</Two>
</Stream>

Here is my c# code :

var XML = from item in XElement.Parse(strXMLStream).Descendants("Stream") select item;
string strOne = string.Empty;
string strTwo = string.Empty;
string strThree =  string.Empty;

if ((item.Element("One").Value != "")
{
   strOne = item.Element("One").Value;
}

if ((item.Element("Two").Value != "")
{
   strTwo = item.Element("Two").Value;
}

if ((item.Element("Three").Value != "")
{
   strThree = item.Element("Three").Value;
}

With this code, if my Stream is full ( Node On, Two and three), there's no problem! But, if my Stream has only the node "Two", I get a NullReferenceException.

Is there a way to avoid this exception (I cannot change my Stream).

Thanks a lot :)

Upvotes: 0

Views: 524

Answers (3)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236248

Instead of accessing Value property (which raises NullReferenceException if element not exist, as you already know) cast elements to strings. You can use ?? to provide default value for non-existing elements:

string strOne = (string)item.Element("One") ?? String.Empty;
string strTwo = (string)item.Element("Two") ?? String.Empty;
string strThree =  (string)item.Element("Three") ?? String.Empty;

Upvotes: 1

Konrad Gadzina
Konrad Gadzina

Reputation: 3404

You should check if item.Element("anything") is null before accessing it's Value property.

if (item.Element("Three") != null && item.Element("Three").Value != "")

Upvotes: 1

DaveShaw
DaveShaw

Reputation: 52798

You need to do:

if (item.Element("One") != null)
{
   strOne = item.Element("One").Value;
}

.Element(String) returns null if an element of the name you requested does not exist.

Checking if value != "" is pointless, because all you are preventing is the reassignment of an empty string to the strOne variable, which is already an empty string. Also, if you really needed to do the empty string check, using String.IsNullOrEmpty(String) method is the preferred way.

Upvotes: 1

Related Questions