views:

29

answers:

1

FYI, This is very similar to my last question: Is there a faster way to check for an XML Element in LINQ to XML, and parse a bool?

Currently I'm using the following extension method that I made to retrieve the int 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 parses the value for an int. Otherwise, it returns 0.

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 could change it to try parse, but for now I'm assuming that if the element is there, then the parsing should succeed.

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 int value of the child element if it exists, or 0 if it doesn't.</returns>
public static int GetIntFromChildElement(this XElement x, string elementName)
{
    return x.Elements(elementName).Any() ? int.Parse(x.Element(elementName).Value) : 0;
}
A: 

Based on Jon Skeet's answer to the original string version of this question, I came up with this:

return int.Parse(((string)x.Element(elementName)) ?? "0");

I'm not sure if that is technically faster though...?

If there is an element, it only does one check for the element, but if the element doesn't exist, then it has to parse the "0" string.

SkippyFire