tags:

views:

76

answers:

2
var doc = XDocument.Parse(inputXML);

this bombs out when "amount" node is not present. How can I check for existence prior to evaluating?

 decimal amt;
 var amount = doc.Descendants("amount").SingleOrDefault().Value;
 bool amountValid = decimal.TryParse(amount, out amt);

I need to make sure "amount" is available prior to evaluating.

Can anyone help?

Thanks All, ~ck in San Diego

+1  A: 

Try this:

var amountElement = doc.Descendants("amount").SingleOrDefault();

if (amountElement != null)
{
    decimal amt;
    bool amountValid = decimal.TryParse(amountElement.Value, out amt);

    // other code
}
Ben M
this worked nicely. Thanks!
Hcabnettek
+2  A: 

XElement provides explicit casts for most value types, including Nullable<Decimal>:

var amt = (decimal?)doc.Descendants("amount").SingleOrDefault();

From there you can check if amt is null or use its HasValue property.

Update: It's worth pointing out that the cast will throw a FormatException if the value is not a Decimal. If you still want to use TryParse, you can keep the code simple with a string cast:

decimal amt;
var amount = (string)doc.Descendants("amount").SingleOrDefault();
bool amountValid = decimal.TryParse(amount, out amt);

Internally, the string cast is implemented like Ben's sample, returning either null or element.Value.

dahlbyk
+1: Didn't know that--great tip! I'm constantly impressed with how well-thought-out XLinq is.
Ben M