目前我正在使用以下扩展方法来检索使用LINQ to XML的元素值。它使用Any()
来查看是否有任何具有给定名称的元素,如果有,则只获取值。否则,它返回一个空字符串。这个方法的主要用途是当我将XML解析为C#对象时,所以当一个元素不在时,我不希望任何东西爆炸。
我有其他数据类型的其他扩展方法,如bool,int和double,以及一些用于将自定义字符串解析为枚举或bool的自定义方法。我也有相同的方法来处理属性。
有一个更好的方法吗?
/// <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;
}
怎么样:
return ((string) x.Element(elementName)) ?? "";
换句话说,找到第一个元素或返回null,然后调用字符串转换运算符(对于null输入将返回null),如果所有这些的结果为null,则默认为空字符串。
您可以将其拆分而不会降低效率 - 但主要的是它只需要查找一次元素。