简体   繁体   English

如何在C#中使用LINQ to XML检查XDocument中属性的存在

[英]How to check the existence of Attribute in XDocument using LINQ to XML in C#

i'm having an xml file like 我有一个像

 <Root>
   <Child Name="A" />
 </Root>

i need to check whether the "Child" element have "val" attribute.if yes , and if the value is greater than zero then need to change the value of a Boolean variable into true; 我需要检查“ Child”元素是否具有“ val”属性。如果是,并且该值大于零,则需要将布尔变量的值更改为true;

now i'm using like 现在我正在使用像

bool bVal=false

bVal=XDocument.Load(Application.StartupPath+"\\foo.xml")
          .Descendants("Child")
          .Select(TEMP => (Int32)TEMP.Attribute("val")).ToList()[0]>0?true:false;

this expression is working fine if xml is like 如果xml像这样,则此表达式工作正常

<Root>
  <Child Name="A" val ="2" />
</Root>

but its throwing an exception if the xml does not contain "val" attribute. 但是如果xml不包含“ val”属性,则抛出异常。

How to modify the above expression(Query) to check the existence of "val" attribute. 如何修改以上表达式(查询)以检查“ val”属性的存在。

In this case, I'd rewrite the query as: 在这种情况下,我将查询重写为:

bool bVal = XDocument.Load(Application.StartupPath+"\\foo.xml")
                     .Descendants("Child")
                     .Select(x => (int?) x.Attribute("val"))
                     .FirstOrDefault(x => x != null) > 0;

This uses three features: 它使用三个功能:

  • Converting XAttribute to int? XAttribute转换为int? instead of int will result in the null value if the attribute isn't present 如果属性不存在,则使用int代替int将导致返回null
  • Using FirstOrDefault instead of ToList()[0] is more efficient and works even if there are no values 使用FirstOrDefault代替ToList()[0]更有效即使没有值也可以使用
  • The lifted > operator will return False when either operand is null 当任一操作数为null时,lifted >运算符将返回False

If you want to check whether there any positive values, it's even easier: 如果要检查是否有任何正面价值观,那就更简单了:

bool bVal = XDocument.Load(Application.StartupPath+"\\foo.xml")
                     .Descendants("Child")
                     .Select(x => (int?) x.Attribute("val"))
                     .Any(x => x > 0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM