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?
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.
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.
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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With