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

仅供参考,这与我的上一个问题非常相似:Is there a faster way to check for an XML Element in LINQ to XML, and parse a bool?

目前,我正在使用以下扩展方法来检索使用 LINQ to XML 的元素的 int 值。它使用 Any() 来查看是否有任何具有给定名称的元素,如果有,它会解析一个 int 的值。否则返回 0。

此方法的主要用途是当我将 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 int value of the child element if it exists, or 0 if it doesn't.</returns>
public static int GetIntFromChildElement(this XElement x, string elementName)
{
    return x.Elements(elementName).Any() ? int.Parse(x.Element(elementName).Value) : 0;
}

【问题讨论】:

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


    【解决方案1】:

    基于 Jon Skeet 对这个问题的原始字符串版本的回答,我想出了这个:

    return int.Parse(((string)x.Element(elementName)) ?? "0");
    

    我不确定这在技术上是否更快......?

    如果有元素,它只检查一次元素,但如果元素不存在,则必须解析"0"字符串。

    【讨论】:

      猜你喜欢
      • 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
      相关资源
      最近更新 更多