Question

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?

Was it helpful?

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.

OTHER TIPS

Not sure exactly the reason, but with C# extension methods, you can solve the problem yourself.

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

Allows:

element.GetAttributeValue("myAttributeName");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top