开发者

Is there a faster way to check for an XML Element in LINQ to XML, and parse a bool?

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 w开发者_开发百科ant 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;
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜