Retrocoder
Retrocoder

Reputation: 4713

linq to xml, handling empty tags

The following link statement works fine if the source XML contains a number or if the tags are missing. The problem I have is when the tags are empty or if a non-numeric value is used. Can this statement be modified to handle these situations ?

Convert.ToInt32((string)Data.Elements("groupBy").Elements("depth").FirstOrDefault() ?? "0")

Upvotes: 0

Views: 190

Answers (2)

Kugel
Kugel

Reputation: 19824

I would simply do:

try
    int result = (int)Data.Elements("groupBy").Elements("depth").FirstOrDefault();
catch
{
    // handle
}

Upvotes: 0

Steve
Steve

Reputation: 15736

Don't know of a way to solve this with LINQ but if you cannot guarantee the content of the XML document then would it be easier to just use int.TryParse()?, e.g.

int result = 0;
int.TryParse((string)Data.Elements("groupBy").Elements("depth").FirstOrDefault(), out result);

Upvotes: 1

Related Questions