【发布时间】: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