这是我的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>
如果存在特定的argument
属性,我正在尝试使用此linq语句来获取value
元素key
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)
或类似的东西替换它吗?
感谢
答案 0 :(得分:1)
在if语句中,您可以写
if (AttrVal != null && AttrVal.Any())
编辑:我错了。异常应该来自First(),而不是任何Elements()。老答案:
from el in root.Descendants("argument")
或
from el in root.XPathSelectElements("./Script/arguments/argument")
答案 1 :(得分:1)
您必须检查元素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"));
}
}
答案 2 :(得分:1)
这是一种消除那些讨厌的空检查的方法 - 提前查找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"));
}