【问题标题】:Is there a faster way to check for an XML Element in LINQ to XML, and parse a bool?是否有更快的方法来检查 LINQ to XML 中的 XML 元素并解析布尔值?
【发布时间】:2010-01-14 16:59:13
【问题描述】:

仅供参考,这与我的上一个问题非常相似:Is there a faster way to check for an XML Element in LINQ to 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 re.compile('.*.*').match(xml.ToString())

标签: xml linq parsing performance linq-to-xml


【解决方案1】:

与上次非常相似:

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

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

这里使用 null-coalescing 运算符意味着整体表达式类型只是bool。

【讨论】:

  • 天哪,我从没想过空合并运算符会这样做!你这个男人。
  • @SkippyFire:null 合并运算符在正确的情况下非常棒。如果我们能得到一个空安全的解引用运算符,那就更好了:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-01
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多