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.
In this case, I’d rewrite the query as:
This uses three features:
XAttributetoint?instead ofintwill result in the null value if the attribute isn’t presentFirstOrDefaultinstead ofToList()[0]is more efficient and works even if there are no values>operator will returnFalsewhen either operand is nullIf you want to check whether there any positive values, it’s even easier: