【问题标题】:Check if any XML nodes exists with Specific Attribute using LINQ C#使用 LINQ C# 检查是否存在具有特定属性的任何 XML 节点
【发布时间】:2023-03-18 15:09:02
【问题描述】:

这是我的 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>

如果存在特定的 key 属性,我正在尝试使用此 linq 语句来获取 argument 元素的 value 属性。

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 (AttrVal.FirstOrDefault() != null)
  • @K.B - 是的,我做到了,但我仍然遇到同样的错误。
  • 您在哪一行收到此错误
  • @K.B - if(!bool.TryParse ...) 行。
  • 在尝试读取其值之前,您需要检查 where 中是否存在该属性 - 请参阅:stackoverflow.com/a/2506840/61470

标签: c# xml linq xelement


【解决方案1】:

在if语句中,可以写

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

编辑:我错了。异常应该来自 First(),而不是 Elements()。旧答案:

from el in root.Descendants("argument")

或者

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

【讨论】:

  • 这能回答你的问题吗?
  • 我在if 语句中实现了AttrVal.Any() 检查,看起来这是我缺少的部分。
  • 对不起。我在您发表评论前几分钟更新了我的答案。
【解决方案2】:

你必须检查元素where el.Attributes("key")!=null&amp;&amp;中是否已经有你的属性

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

【讨论】:

    【解决方案3】:

    这是一种消除那些讨厌的空检查的方法 - 使用XPath 确定是否存在具有两个必要属性(即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"));
         }
    

    【讨论】:

      猜你喜欢
      • 2011-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 2021-06-06
      • 1970-01-01
      • 2012-01-14
      相关资源
      最近更新 更多