XML to LINQ with Checking Null Elements

后端 未结 3 1251
不知归路
不知归路 2021-01-13 16:21

The situation I am faced with is parsing an XML document into an object using Linq. During the parse I am checking to make sure Elements are not null before proceeding to p

3条回答
  •  春和景丽
    2021-01-13 16:35

    In C# 6.0 you can use monadic Null-conditional operator ?. After applying it in your example it would look like this:

    var variable = (from x in xdoc.Descendants("Root")
                    select new
                    {
                        NetCharge = x.Element("Charges")?.Element("NetCharge")?.Value ?? "0",
                        TotalCharge = x.Element("Charges")?.Element("TotalCharge")?.Value ?? "0"
                    }).SingleOrDefault();
    

    You can read more here in part titled Null-conditional operators.

提交回复
热议问题