开发者

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


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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜