Dealing with XElement null value

2019-07-16 11:21发布

I have an xml that I am querying. One of the nodes is missing. So when I call XElement.Value I get a null exception.

What is the best way to guard against this? I know I can write an extension method, but I am wondering is there something build into the language for this?

1条回答
啃猪蹄的小仙女
2楼-- · 2019-07-16 12:13

use the null coalesce operator ??

Given an XElement elem:

var value = (string)elem ?? "empty";
查看更多
登录 后发表回答