【发布时间】:2010-01-14 16:27:13
【问题描述】:
目前我正在使用以下扩展方法来检索使用 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;
}
【问题讨论】:
标签: c# xml linq parsing linq-to-xml