2
目前我正在使用以下扩展方法来检索使用LINQ to XML的元素值。它使用Any()
来查看是否有任何具有给定名称的元素,如果有,它只是获取该值。否则,它将返回一个空字符串。这个方法的主要用途是当我将XML解析为C#对象时,所以当一个元素不在时,我不希望任何东西爆炸。有更快的方法来检查LINQ to XML中的XML元素吗?
我有其他扩展方法的其他数据类型,如bool,int和double,以及一些自定义字符串解析为枚举或布尔的自定义字符串。我也有相同的方法来处理属性。
有没有更好的方法来做到这一点?
/// <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 value of the child element if it exists, or an empty string if it doesn't.</returns>
public static string GetStringFromChildElement(this XElement x, string elementName)
{
return x.Elements(elementName).Any() ? x.Element(elementName).Value : string.Empty;
}
所以我猜是将一个XML元素转换为一个字符串去返回值? – 2010-01-14 16:35:13
另外,是否有一个原因,你选择“”而不是string.Empty? – 2010-01-14 16:43:31
刚刚确认将元素转换为字符串确实会返回值。 – 2010-01-14 16:55:34