Search code examples
c#linqxelementsystem.xml

Why doesn't XElement have a GetAttributeValue method?


Sometimes I'd like to know the reasoning of certain API changes. Since Google hasn't helped me with this question, maybe StackOverflow can. Why did Microsoft choose to remove the GetAttribute helper method on XML elements? In the System.Xml world there was XmlElement.GetAttribute("x") like getAttribute in MSXML before it, both of which return either the attribute value or an empty string when missing. With XElement there's SetAttributeValue but GetAttributeValue wasn't implemented.

Certainly it's not too much work to modify logic to test and use the XElement.Attribute("x").Value property but it's not as convenient and providing the utility function one way (SetAttributeValue) but not the other seems weird. Does anyone out there know the reasons behind the decision so that I can rest easily and maybe learn something from it?


Solution

  • You are supposed to get attribute value like this:

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

    UPDATE:

    Examples:

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

    etc.

    See this article: http://www.hanselman.com/blog/ImprovingLINQCodeSmellWithExplicitAndImplicitConversionOperators.aspx. Same thing works for attributes.