[英]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.