2010-08-04 191 views
13

有時我想知道某些API更改的推理。由於谷歌沒有幫助我解決這個問題,可能是StackOverflow。爲什麼Microsoft選擇刪除XML元素上的GetAttribute輔助方法?在System.Xml世界中,有XmlElement.GetAttribute("x")之前的MSXML中的getAttribute,兩者都在缺失時返回屬性值或空字符串。有XElementSetAttributeValueGetAttributeValue沒有實施。爲什麼XElement沒有GetAttributeValue方法?

當然,修改邏輯來測試和使用XElement.Attribute("x").Value屬性並沒有太多的工作,但它不那麼方便,並且提供了一種方式的效用函數(SetAttributeValue),但其他的看起來很奇怪。有沒有人知道決定背後的原因,讓我可以輕鬆休息,也許可以從中學到些什麼?

回答

15

你應該得到的屬性值是這樣的:

var value = (TYPE) element.Attribute("x"); 

UPDATE:

例子:

var value = (string) element.Attribute("x"); 
var value = (int) element.Attribute("x"); 

參見這篇文章:http://www.hanselman.com/blog/ImprovingLINQCodeSmellWithExplicitAndImplicitConversionOperators.aspx。同樣的東西適用於屬性。

+0

返回XAttribute的一個實例。不知道如何將它轉換爲System.Type將會有所幫助。 – 2010-08-04 23:28:18

+0

不是System.Type大聲笑,無論你需要它的類型。我會更新我的答案。 – Necros 2010-08-04 23:30:56

+1

不錯,不知道這些類的類型轉換。謝謝! – 2010-08-04 23:36:06

5

不確定原因,但使用C#擴展方法,您可以自己解決問題。

public static string GetAttributeValue(this XElement element, XName name) 
{ 
    var attribute = element.Attribute(name); 
    return attribute != null ? attribute.Value : null; 
} 

允許:

element.GetAttributeValue("myAttributeName"); 
+4

我經常最終做這個功能的本質,當然這是最好的辦法國際海事組織,但我有興趣*爲什麼* GetAttribute從API中缺少時,它已經在以前的模型中,他們提供了一個幫手setter – 2010-08-05 00:11:30

相關問題