Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 349
John Lewin Avatar asked Aug 04 '10 23:08

John Lewin


People also ask

How do I get XElement attribute value?

Value: If you are getting the value and the attribute might not exist, it is more convenient to use the explicit conversion operators, and assign the attribute to a nullable type such as string or Nullable<T> of Int32 . If the attribute does not exist, then the nullable type is set to null.

What is XElement?

The XElement class is one of the fundamental classes in LINQ to XML. It represents an XML element. The following list shows what you can use this class for: Create elements. Change the content of the element.


2 Answers

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.

like image 106
Necros Avatar answered Oct 03 '22 21:10

Necros


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");
like image 24
Kirk Woll Avatar answered Oct 03 '22 20:10

Kirk Woll