views:

48

answers:

1

FYI, This is very similar to my last question: Is there a faster way to check for an XML Element in LINQ to XML?

Currently I'm using the following extension method that I made to retrieve the bool values of elements using LINQ to XML. It uses Any() to see if there are any elements with the given name, and if there are, it parses the value for a bool. Otherwise, it returns false. The main use for this method is for when I'm parsing XML into C# objects, so I don't want anything blowing up when an element is not there. I could change it to try parse, but for now I'm assuming that if the element is there, then the parsing should succeed.

Is there a better way to do this?

/// <summary>
/// If the parent element contains a element of the specified name, it returns the value of that element.
/// </summary>
/// <param name="x">The parent element.</param>
/// <param name="elementName">The name of the child element to check for.</param>
/// <returns>The bool value of the child element if it exists, or false if it doesn't.</returns>
public static bool GetBoolFromChildElement(this XElement x, string elementName)
{
    return x.Elements(elementName).Any() ? bool.Parse(x.Element(elementName).Value) : false;
}
+4  A: 

Very similar to last time:

return ((bool?) x.Element(elementName)) ?? false;

Note the use of the conversion to the nullable Boolean type, rather than the non-nullable version; the non-nullable version will throw an exception if the input is null.

Using the null-coalescing operator here means the overall expression type is just bool.

Jon Skeet
Holy cow, I never thought that the null-coalescing operator would do that! You the man.
SkippyFire
@SkippyFire: The null coalescing operator is awesome in the right situations. If we ever get a null-safe dereferencing operator, it'll be even better :)
Jon Skeet