开发者

linq to xml, handling empty tags

开发者 https://www.devze.com 2023-01-28 00:54 出处:网络
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 statem

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")


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);


I would simply do:

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

精彩评论

暂无评论...
验证码 换一张
取 消