Is there a faster way to check for an XML Element

2019-07-18 04:51发布

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;
}

1条回答
何必那么认真
2楼-- · 2019-07-18 05:45

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.

查看更多
登录 后发表回答