tags:

views:

76

answers:

1

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;

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

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

but its throwing an exception if the xml does not contain "val" attribute.

How to modify the above expression(Query) to check the existence of "val" attribute.

+3  A: 

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? instead of int will result in the null value if the attribute isn't present
  • Using FirstOrDefault instead of ToList()[0] is more efficient and works even if there are no values
  • The lifted > operator will return False when either operand is null

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);
Jon Skeet
@ Jon Skeet: Thank you..:-)
Pramodh