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;
}