2010-01-14 59 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

相關問題