仅供参考,这是非常类似于我的最后一个问题: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;
}
你可以使用正则表达式来达到特定的目的。返回re.compile('。* <'+ elementName +'>。*')。match(xml.ToString()) – 2010-01-14 17:06:48