簡體   English   中英

使用 XDocument 檢查文件中是否存在 xml 部分

[英]Check if an xml section exist in a file using XDocument

我有一些讀入 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]部分,它不會 go 進入語句,因此我不應該得到這個錯誤。 有沒有辦法先檢查一個部分是否存在?

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

在這個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子句鏈。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM