簡體   English   中英

使用LINQ C#檢查是否存在具有特定屬性的XML節點

[英]Check if any XML nodes exists with Specific Attribute using LINQ C#

這是我的XML:

<configuration>
    <Script name="Test Script">
        <arguments>
            <argument key="CheckStats" value="True" />
            <argument key="ReferenceTimepoint" value="SCREENING" />
            <argument key="outputResultSetName" value="ResultSet" />
        </arguments>
    </Script>
</configuration>

我正在嘗試使用此linq語句在特定key屬性存在的情況下獲取argument元素的value attrbiute。

XElement root = XElement.Load(configFileName);
var AttrVal = from el in root.Elements("Script").Elements("arguments").Elements("argument")
            where el.Attribute("key").Value == "CheckStats"
            select el.Attribute("value").Value;

然后,我想嘗試將屬性value解析為布爾值:

bool checkVal;
if (AttrVal != null)
{
    if (!bool.TryParse(AttrVal.First().ToString(), out checkVal))
    {
        throw new Exception(string.Format("Invalid value"));
    }
}

如果有一個具有該屬性的元素,則此代碼有效,但如果沒有,則得到System.InvalidOperationException: Sequence contains no elements

我該如何解決? 我認為通過檢查if (AttrVal != null)是否可以工作。 我應該用if (AttrVal.FirstOrDefault() != null)或類似的東西替換它嗎? 謝謝

在if語句中,您可以編寫

if (AttrVal != null && AttrVal.Any())

編輯 :我錯了。 異常應該來自First(),而不是任何Elements()。 舊答案:

from el in root.Descendants("argument")

要么

from el in root.XPathSelectElements("./Script/arguments/argument")

您必須檢查where el.Attributes("key")!=null&&元素where el.Attributes("key")!=null&&是否已經有您的屬性。

XElement root = XElement.Load("config.xml");
            var AttrVal = from el in root.Elements("Script").Elements("arguments").Elements("argument")
                          where el.Attributes("key")!=null&&  el.Attribute("key").Value == "CheckStats"
                          select el.Attribute("value").Value;

            bool checkVal;
            if (AttrVal != null)
            {
                if (!bool.TryParse(AttrVal.First().ToString(), out checkVal))
                {
                    throw new Exception(string.Format("Invalid value"));
                }
            }

這是消除那些討厭的空檢查的一種方法-繼續尋找XPath以確定是否同時具有兩個必需屬性(即viz key="CheckStats"value )的節點,然后對其進行解析。

     bool checkVal;

     // using System.Xml.XPath;!
     var el = root.XPathSelectElement(
                    "/Script/arguments/argument[@key='CheckStats' and @value]");
     if (el != null && !bool.TryParse(el.Attribute("value").Value, 
         out checkVal))
     {
        throw new Exception(string.Format("Invalid value"));
     }

暫無
暫無

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

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