Hcabnettek
Hcabnettek

Reputation: 12928

LinqToXML, breaking when Node doesn't exist. How do I check for existence?

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

Upvotes: 1

Views: 179

Answers (2)

dahlbyk
dahlbyk

Reputation: 77540

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.

Upvotes: 2

Ben M
Ben M

Reputation: 22492

Try this:

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

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

    // other code
}

Upvotes: 1

Related Questions