views:

52

answers:

1

Currently I'm using the following extension method that I made to retrieve the values of elements using LINQ to XML. It uses Any() to see if there are any elements with the given name, and if there are, it just gets the value. Otherwise, it returns an empty string. The main use for this method is for when I'm parsing XML into C# objects, so I don't want anything blowing up when an element is not there.

I have other extension methods for the other data type like bool, int and double, and some custom ones for parsing custom strings into enums or bools. I also have those same methods for working with attributes.

Is there a better way to do this?

/// <summary>
/// If the parent element contains a element of the specified name, it returns the value of that element.
/// </summary>
/// <param name="x">The parent element.</param>
/// <param name="elementName">The name of the child element to check for.</param>
/// <returns>The value of the child element if it exists, or an empty string if it doesn't.</returns>
public static string GetStringFromChildElement(this XElement x, string elementName)
{
    return x.Elements(elementName).Any() ? x.Element(elementName).Value : string.Empty;
}
+3  A: 

How about:

return ((string) x.Element(elementName)) ?? "";

In other words, find the first element or return null, then invoke the string conversion operator (which will return null for null input) and default to an empty string if the result of all of this is null.

You could split that out without any loss of efficiency - but the main thing is it only needs to look for the element once.

Jon Skeet
So I'm guessing that casting an XML Element to a string going to return the value?
SkippyFire
Also, is there a reason you chose "" instead of string.Empty?
SkippyFire
Just confirmed that casting the element to a string does return the value.
SkippyFire
@SkippyFire: I generally find "" more readable. It'll do the same thing, of course. And yes, that cast will invoke the explicit conversion to string - see MSDN documentation for details.
Jon Skeet
Awesome. Thanks again Jon.
SkippyFire