Click here to Skip to main content
15,867,568 members
Articles / Programming Languages / XML
Alternative
Tip/Trick

Using Extension Methods To Avoid XML Problems

Rate me:
Please Sign up or sign in to vote.
5.00/5 (4 votes)
17 May 2010CPOL 7.9K   1   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)


Written By
Architect
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralYou can replace the ".Elements(name).FirstOrDefault()" with ... Pin
Richard Deeming25-Jan-11 10:23
mveRichard Deeming25-Jan-11 10:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.