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