为什么XElement没有GetAttributeValue方法?

Joh*_*win 13 c# linq xelement system.xml

有时我想知道某些API更改的原因.由于谷歌没有帮助我解决这个问题,也许StackOverflow可以.为什么Microsoft选择删除GetAttributeXML元素上的辅助方法?在System.Xml世界上有XmlElement.GetAttribute("x")类似于getAttribute之前的MSXML,它们都会在缺失时返回属性值或空字符串.随着XElementSetAttributeValue,但GetAttributeValue没有实现.

当然,修改逻辑来测试和使用XElement.Attribute("x").Value属性并不是太多的工作,但它不是那么方便,并且提供实用功能的一种方式(SetAttributeValue)而不是另一种似乎很奇怪.有没有人知道决定背后的原因,以便我可以轻松地休息,也许从中学到一些东西?

Nec*_*ros 16

你应该得到这样的属性值:

var value = (TYPE) element.Attribute("x");
Run Code Online (Sandbox Code Playgroud)

更新:

例子:

var value = (string) element.Attribute("x");
var value = (int) element.Attribute("x");
Run Code Online (Sandbox Code Playgroud)

等等

请参阅此文章:http://www.hanselman.com/blog/ImprovingLINQCodeSmellWithExplicitAndImplicitConversionOperators.aspx.同样适用于属性.

  • 我刚刚在这里评论了这个主题(http://mo.notono.us/2010/08/xelement-xattribute-and-explicit.html),但我坚持认为显式类型转换运算符是坏的事情.它们没有智能感,它们看起来就像一个花园品种. - 柯克的困惑是完全可以理解的.即使转换运算符存在,我想我会更喜欢扩展方法,只是因为它明确显而易见它的作用...... PS!请注意,如果属性或元素可能不存在,则需要使用可空类型转换. (6认同)
  • 很好,不知道这些类的类型转换。谢谢! (2认同)

Kir*_*oll 5

不确定原因,但使用C#扩展方法,您可以自己解决问题.

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

允许:

element.GetAttributeValue("myAttributeName");
Run Code Online (Sandbox Code Playgroud)

  • 我经常最终基本上做了这个函数的功能,当然这是IMO的最佳方法,但是我感兴趣的是*为什么*API在以前的模型中存在时缺少了GetAttribute并且它们为setter提供了一个帮助器 (4认同)