Reputation: 14682
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.
Upvotes: 1
Views: 4322
Reputation: 1500865
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:
XAttribute
to int?
instead of int
will result in the null value if the attribute isn't presentFirstOrDefault
instead of ToList()[0]
is more efficient and works even if there are no values>
operator will return False
when either operand is nullIf 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);
Upvotes: 6