目前,我正在使用以下扩展方法来检索使用 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,则默认为空字符串。
您可以在不损失任何效率的情况下将其拆分 - 但主要的是它只需要查找一次元素。
关于c# - 有没有更快的方法来检查 LINQ to XML 中的 XML 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2065665/