Click here to Skip to main content
Click here to Skip to main content
Alternative Tip

Tagged as

Go to top

Using Extension Methods To Avoid XML Problems

, 17 May 2010
Rate this:
Please Sign up or sign in to vote.
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:
 
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. Smile | :)

License

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

Share

About the Author

Rama Krishna Vavilala
Architect
United States United States
No Biography provided

Comments and Discussions

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

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

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

| Advertise | Privacy | Mobile
Web02 | 2.8.140922.1 | Last Updated 17 May 2010
Article Copyright 2010 by Rama Krishna Vavilala
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid