2010-08-04 52 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

相关问题