有没有更快的方法来检查LINQ to XML中的XML元素并解析布尔值? [英] Is there a faster way to check for an XML Element in LINQ to XML, and parse a bool?

查看:64
本文介绍了有没有更快的方法来检查LINQ to XML中的XML元素并解析布尔值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅供参考,这与我的上一个问题非常相似:

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

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

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.

有更好的方法吗?

/// <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,则非null版本将引发异常.

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.

在这里使用null-coalescing运算符意味着整个表达式类型仅为bool.

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

这篇关于有没有更快的方法来检查LINQ to XML中的XML元素并解析布尔值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆