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;
}
所以我猜是將一個XML元素轉換爲一個字符串去返回值? – 2010-01-14 16:35:13
另外,是否有一個原因,你選擇「」而不是string.Empty? – 2010-01-14 16:43:31
剛剛確認將元素轉換爲字符串確實會返回值。 – 2010-01-14 16:55:34