2010-01-14 61 views
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; 
} 

回答

3

如何:

return ((string) x.Element(elementName)) ?? ""; 

换句话说,找到的第一个元素或返回null,然后调用字符串转换操作符(这将返回null为空输入),默认为空字符串如果所有这些的结果为空。

你可以分割出来,而不会损失任何效率 - 但主要的是它只需要查找一次元素。

+0

所以我猜是将一个XML元素转换为一个字符串去返回值? – 2010-01-14 16:35:13

+2

另外,是否有一个原因,你选择“”而不是string.Empty? – 2010-01-14 16:43:31

+0

刚刚确认将元素转换为字符串确实会返回值。 – 2010-01-14 16:55:34

相关问题