2010-01-14 67 views
2

仅供参考,这是非常类似于我的最后一个问题:Is there a faster way to check for an XML Element in LINQ to XML?有没有更快的方法检查LINQ to XML中的XML元素,并解析一个bool?

当前我使用以下扩展方法,我使用LINQ to XML检索元素的布尔值。它使用Any()来查看是否有任何具有给定名称的元素,如果存在,它将分析bool的值。否则,它返回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; 
} 
+0

你可以使用正则表达式来达到特定的目的。返回re.compile('。* <'+ elementName +'>。*')。match(xml.ToString()) – 2010-01-14 17:06:48

回答

4

非常相似,最后一次:

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

注意使用转化为可空布尔类型,而不是不可为空的版本;如果输入为空,则不可为空的版本将引发异常。

这里使用空合并运算符意味着整体表达式类型只是bool

+0

圣牛,我从来没有想过null-coalescing操作符会这样做!你是那个人。 – 2010-01-14 19:09:02

+0

@SkippyFire:在合适的情况下,空合并操作符非常棒。如果我们得到一个无效的解引用操作符,它会更好:) – 2010-01-14 19:55:16

相关问题