0

我有一些读取 xml 文件的代码。但是它在第三个 IF 语句中触发了一个错误:

if (xdoc.Root.Descendants("HOST").Descendants("Default")
    .FirstOrDefault().Descendants("HostID")
    .FirstOrDefault().Descendants("Deployment").Any())

错误:

System.NullReferenceException: Object reference not set to an instance of an object.

那是因为在这个特定的文件中没有[HOST]节。

我假设在第一个 IF 语句中,如果它没有找到任何[HOST]部分,它就不会进入语句,因此我不应该得到这个错误。有没有办法先检查一个部分是否存在?

XDocument xdoc = XDocument.Load(myXmlFile);

if (xdoc.Root.Descendants("HOST").Any())
{
    if (xdoc.Root.Descendants("HOST").Descendants("Default").Any())
    {
        if (xdoc.Root.Descendants("HOST").Descendants("Default").FirstOrDefault().Descendants("HostID").FirstOrDefault().Descendants("Deployment").Any())
        {
            if (xdoc.Root.Descendants("HOST").Descendants("Default").FirstOrDefault().Descendants("HostID").Any())
            {
                var hopsTempplateDeployment = xdoc.Root.Descendants("HOST").Descendants("Default").FirstOrDefault().Descendants("HostID").FirstOrDefault().Descendants("Deployment").FirstOrDefault();
                deploymentKind = hopsTempplateDeployment.Attribute("DeploymentKind");
                host = hopsTempplateDeployment.Attribute("HostName");
            }
        }
    }
}
4

1 回答 1

1

在这个if块的主体内......

if (xdoc.Root.Descendants("HOST").Descendants("Default").Any())
{
    if (xdoc.Root.Descendants("HOST").Descendants("Default").FirstOrDefault().Descendants("HostID").FirstOrDefault().Descendants("Deployment").Any())
    {
        if (xdoc.Root.Descendants("HOST").Descendants("Default").FirstOrDefault().Descendants("HostID").Any())
        {
            var hopsTempplateDeployment = xdoc.Root.Descendants("HOST").Descendants("Default").FirstOrDefault().Descendants("HostID").FirstOrDefault().Descendants("Deployment").FirstOrDefault();
            deploymentKind = hopsTempplateDeployment.Attribute("DeploymentKind");
            host = hopsTempplateDeployment.Attribute("HostName");
        }
    }
}

...您已确定该元素<Root>/HOST/Default存在。但是你不知道是否<Root>/HOST/Default/HostId/Deployment存在。如果不是NullReferenceException这样,您会因为使用FirstOrDefault. 通常建议First在您期望元素存在的情况下使用,这将至少为您提供更好的错误消息。

如果您希望元素不存在,一个简单的解决方案是?.沿各自的 LINQ2XML 轴使用:

var hopsTemplateDeployment =
    xdoc.Root.Descendants("HOST").Descendants("Default").FirstOrDefault()
    ?.Descendants("HostID").FirstOrDefault()
    ?.Descendants("Deployment").FirstOrDefault();
if (hopsTemplateDeployment != null)
{
    deploymentKind = hopsTemplateDeployment.Attribute("DeploymentKind");
    host = hopsTemplateDeployment.Attribute("HostName");
}

它还将为您节省嵌套if子句链。

于 2019-10-23T13:11:35.200 回答