在LINQ to XML中是否有更快的方法来检查XML元素,并解析出一个bool?[英] Is there a faster way to check for an XML Element in LINQ to XML, and parse a bool?

本文是小编为大家收集整理的关于在LINQ to XML中是否有更快的方法来检查XML元素,并解析出一个bool?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

仅供参考,这与我的上一个问题非常相似:是否有更快的方法来检查 LINQ to XML 中的 XML 元素?

目前我正在使用以下扩展方法来检索使用 LINQ to XML 的元素的布尔值.它使用 Any() 查看是否有任何具有给定名称的元素,如果有,它会解析布尔值.否则,它返回 false.此方法的主要用途是当我将 XML 解析为 C# 对象时,所以我不希望当元素不存在时发生任何事情.我可以更改它以尝试解析,但现在我假设如果元素存在,那么解析应该成功.

有没有更好的方法来做到这一点?

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

推荐答案

和上次很像:

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

注意使用转换为可空的布尔类型,而不是不可空的版本;如果输入为空,不可为空的版本会抛出异常.

这里使用null-coalescing 操作符意味着整个表达式类型只是bool.

本文地址:https://www.itbaoku.cn/post/1556762.html

问题描述

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

推荐答案

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.