【发布时间】: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