如何处理Linq-To-Xml中的null,空白或无Element问题?

问题描述 投票:0回答:1

我在下面的查询中收到关于可能的system.NullReferenceException的警告,其中代码为el.Attribute("id").Value。如何更改此查询以处理这种可能性?

var RentAssumptionPreScreen = xdoc.Descendants("Rent")
    .Single(el => el.Attribute("id").Value == "11162")
    .Parent.Descendants("Value").Single().Value;
System.NullReferenceException: 'Object reference not set to an instance of an object.'
c# .net linq-to-xml
1个回答
0
投票

您可以尝试以下方法:

var RentAssumptionPreScreen = xdoc.Descendants("Rent")
    .FirstOrDefault(el => el.Attribute("id")?.Value == "11162")?
    .Parent.Descendants("Value").FirstOrDefault()?.Value;
© www.soinside.com 2019 - 2024. All rights reserved.