Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / XML

Using Extension Methods To Avoid XML Problems

5.00/5 (4 votes)
17 May 2010CPOL 1  
I will just make it a little more compact by omitting the Contains method:public static string GetValue(this XElement root, string name, string defaultValue) { return (string)root.Elements(name).FirstOrDefault() ?? defaultValue; }The explicit operators for XElement...
I will just make it a little more compact by omitting the Contains method:

C#
public static string GetValue(this XElement root, string name, string defaultValue)
    {
        return (string)root.Elements(name).FirstOrDefault() ?? defaultValue;
    }



The explicit operators for XElement and XAttribute are pretty handy.

This works for SilverLight too (you need to add an assembly reference to System.Core)

----------

FROM JSOP: I already have that rfeerence, and FirstOrDefault still isn't available.

FROM VRK: Did you forget adding using System.Linq; to your namespace imports?

FROM JSOP: I got around to playing with the code again, and you're right, I didn't the using System.Linq; in there. I voted your message a 5 because it improved the code, but I didn't mark it as accept alternate, because technically, you didn't change the base aspect of the tip which was to extend the functionality via an extension method to avoid the inevitable exception, and I actually use the Contains method without the GetValue method. However, it was a good optimization. :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)